问:
Is it a good habit to use C expressions in C++ code?
At school we started learning C this year, despite the fact I'm way ahead of class, and I learned Java, C++ and C while the class is at the base of C. Anyhow, I've been documenting myself, reading books, articles, and I've asked my teacher why I should learn C, and she said it was the foundation of C++. When I first started programming I found C++ alot easier, I later on learned C. But In books you can see that C code works in C++ yet it doesn't go vice-versa.

My question is pretty straightforward ~ Is it a good habit to use C expressions in C++? Let me give you an example:

Should this code

```<code>#include <stdio.h>
#include <iostream>

int main() {
int x;
scanf("%d", &x);
cout << "The number you entered is " << x << "And it's double is " << x*x;
return 0;
}
</code>```

Be more efficient or better in any way than this:

```<code>#include <iostream>

int main() {
int x;
cin >> x;
cout << "The number you entered is " << x << "And it's double is " << x*x;
return 0;
}
</code>```

I have already done some easy documentation on this in some dusty old books, and from what I could find, using scanf instead of cout also flushes the stream or something like that, so I'm basically asking if it's better to use scanf and in what contexts.

This also applies to file IO as I've always found FIle IO to be easier in C than in C++. This question goes for pretty much every general expression in C applied to C++. It's also notable that I'm using a modern compiler and nevertheless this should not matter as I'm asking if it's a good programming habit to use C expressions in C++ code.

There are probably cons and pros of doing this, but I'm only looking for a yes/why, no/why type of answer.

Also if there are any details I've left out post a comment.

答:
If we put aside the coding style and esthetic issues, there are also various technical problems that you face when using C in C++ code:

What is C? C90, C99 or C11? There may be various compatibility issues depending on which C standard you are using. Boolean type, // comments, C99 features like VLAs, designated initializers etc.

C++ has stricter typing than C. In order to compile C code in C++, you must most likely add various typecasts to get the expected type. This means that you might have to rewrite perfectly fine, production-quality C code to get it working in C++.

The typecasts enfored by stricter typing are generally just a good thing, but in some cases they can introduce or hide away bugs. Take the infamous cast of the result from malloc() as an example. This should be typecasted in C++, but never in C. (1)

Mixing C and C++ functionality can lead to bugs and undefined behavior. For example, it will not work to allocate with malloc() and freeing with delete. (2)

Thread safety issues. The C standard library is not thread safe. The standard C++ library may or may not be thread safe, if it is, then adding C library function calls to your code will destroy that.

As a sidenote for Windows programmers: the Visual C++ compiler had a leak bug for quite some time, when the Windows API CreateThread() function was used in the same program as the C library. (3, 4)

Calling convention might be an issue on some compilers, forcing one to use extern "C" to explicitly tell which functions that should be linked with "C calling convention".

Annoying details. Comma operator behaves differently. Trailing comma in struct/enum declarations is allowed in C99/C11 but not C++. The scope of various kinds of variables and functions are treated differently. Etc etc.

There are likely even more cases.

References:

http://c-faq.com/malloc/cast.html

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3

http://www.flounder.com/badprogram.htm#CreateThread

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx


问:
Separation of Concerns when adding new types
I have a system I've been working on this week where I'm having a hard time balancing separation of concerns with easy extensibility.  I'm adding new types to the system, and it feels like shotgun surgery.

The basic idea is that data is collected (polled) from a remote system and then made available to a number of different kinds of clients.  To support their interface type (protocol), I'm doing a lot of translation.

I'm going to try to simplify this so I can fit it in a question box.

There's a FruitService out in the world with an SNMP interface.  My publisher's job is to collect that data and then publish it.

So for each kind of new Fruit we decide to publish, I create a class that knows how to pull the attributes for that fruit via SNMP.

Internally Fruit is translated to DTOs (the same objects used to talk to client #1 (RMI)).

A cache is updated and checked for changes to trigger async notifications.

A class to translate the fruit into the xml schema used by another client (#2).

A class to translate the fruit into simple attribute/value pairs used by another client (#3).

In the end I create 5 classes and edit 8 more to plug in a new type.  It's not a lot of work; couple hours to write code, test, and check-in for a simple type.
Note that there isn't a lot of commonality in the fruit types (e.g.: pear and coconut), so most of the common abstractions are based around the process of updating the data and not the data itself.

My design concerns are:

The SNMP interface changes 2-3 times a year

The xml schema (client 2) changes 10 times a year.

Adding new types happens less frequently, generally when someone gets around to it.  But maybe if it was easier...

So the notional goal with the design was to handle those external changes easily.  This lead to all the separation in the translation layers.  But adding types feels harder than I'd like.

Is there a technique or example I might look into?  An idea I'm missing?  Am I applying SRP wrong and there should be an Apple type that speaks SNNP, xml schema, DTO, etc?

EDIT:

Client #1, the RMI client, is custom written when a new fruit is added, to take advantage of all the fruit's capabilities. So if we decide to pull banana information from the FruitService we will also write a client that allows you to peel the banana, get a notification when it's ripe, and tell you which bunch it belongs to - along with the basic fruit attributes like size, weight, color, time till rotten, etc.

答:
My first impression is that your design needs some refactoring to be more object oriented. You have different types for different structures, however the behaviour is important. If it is possible rather than creating new Fruit type, describe generic Fruit structure and create objects for concrete Fruit. This way you can include behaviour which will describe the structure in Fruit and create generic translation classes, which will just use the information about the structure to create the 8 objects you need when you add new fruit type. This could be done also using metaprogramming, but depends on your language and skills and effort needed to create something like that.

So the idea is to translate Coconut.getMilk() and Pear.getSeeds() into Fruit.getAttributes() and so on. Does this help a bit?

OwnerDisplayName: Steve Jackson

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gabriel Ščerbák


问:
How to store record statuses (like pending, complete, draft, cancelled...)
Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example.

I have a simple Blog application and each post has a status one of: published, draft or pending.

The way i see it there are 2 ways to model this in the database.

The Post table has a text field that includes the status text.

The Post table has a status field that contains the ID of a record in the PostStatus table

The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed.

Can anyone explain the advantages/disadvantages of each?

Cheers!

My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases

答:
The status is very important, any time you get post info you'll need to get it's status, or you'll want to filter posts by status.
If you have status in another table, you'll need to make joins to get this info and so performance is compromised. Definitely you should have status in same table. And put an index on it!
You can still use integers as status, or maybe enum field.</p>

ContentLicense: CC BY-SA 3.0


问:
Is there a specific term for an accessor method that returns a boolean value?
I seem to recall that there is a specific term for an accessor method that returns a Boolean value but it escapes me. For example: typical methods such as:

```<code>class Example {
    bool isDirty();
    bool hasChildren();
    bool isValid(SomeType obj);
};
</code>```

I will also settle for such a term as applied to a non-member functions.

答:
A switch (which is ambiguous), a flag, a bool, a state...  Nothing I can think of is specific to a getter...

Different environments have different conventions...

Ruby: some_object.is_something?

ObjC: [someObject isSomething]

So I guess I support the "is doctrine"...


问:
When are scripts inside HTML not considered a bad practice?
I am new to web development. While studying the Play framework and JSP, I noticed that they both give an option to place script (in jsp scriptlet) inside HTML, but in both books I am reading they both say it is bad practice and don't give an explanation as to when should I use scripts, only writing not to.

My question is, if both frameworks supply such an option, when would it be ok to use scripts inside HTML?

Please note, I'm talking about server side scripts for creating dynamic HTML (i.e. JSP scriptlet).

答:
I can think of several places where I would do this

1) Simple testing of an idea, I want to see how something works and don't intend to keep the code.

2) Data initialization, where the actual program logic is in an external file but I want to load initial data for some reason and don't want to have an ajax call to get it. For example if I have a list of countries that I will need to use that would be a perfect candidate. It will change rarely and can be inserted into the HTML page by way of whatever language I am using server side (PHP, Ruby, Haskell etc), in this case I may have some code like this

```<code>Data.countries = <?php echo json_encode($countries); ?>;
</code>```

Body:
I can think of several places where I would do this

1) Simple testing of an idea, I want to see how something works and don't intend to keep the code.

2) Data initialization, where the actual program logic is in an external file but I want to load initial data for some reason and don't want to have an ajax call to get it. For example if I have a list of countries that I will need to use that would be a perfect candidate. It will change rarely and can be inserted into the HTML page by way of whatever language I am using server side (PHP, Ruby, Haskell etc), in this case I may have some code like this

Data.countries = <?php echo json_encode($countries); ?>;


答:
Using text for status in the record table would probably not be a good idea as this can change and it would be difficult to perform any data integrity checks on insert/update. If you are utilizing a DBMS with an enum datatype, you can use this instead (performance will probably not be compromised ...depending).

If your status needs any metadata (description, created by, friendly name, ...) you will need to store statuses in a separate table and have a status key in your record table (make sure you use a foreign key). The id does not necessarily need to be a number, just the PK of the status table. Also, if the statuses are in their own table, you can share them across record types (tables) if applicable. I wouldn't worry about performance issues with a JOIN to the status table.

Whatever you do, make sure you avoid magic statuses (1 for active, 2 for deleted, ...). This relies on documentation and tradition which always have a tendency to get lost on a large enough timeline. If you are using numeric ids at all, make sure there is a textual association somewhere in your db.

Title: How to store record statuses (like pending, complete, draft, cancelled...)

Body:
Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example.

I have a simple Blog application and each post has a status one of: published, draft or pending.

The way i see it there are 2 ways to model this in the database.

The Post table has a text field that includes the status text.

The Post table has a status field that contains the ID of a record in the PostStatus table

The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed.

Can anyone explain the advantages/disadvantages of each?

Cheers!

My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases


答:
A function from some type T to Boolean is usually called a predicate, and if you want to make clear that it is a method of an object, i.e. that it takes the implicit this argument in addition to its other arguments, then you could call it a predicate method. If it takes no other arguments except the implicit this argument, then you can call it a predicate property.

See for example Predicate<T> in .NET and e.g. javax.sql.rowset.Predicate or com.google.common.base.Predicate in Java.

Title: Is there a specific term for an accessor method that returns a boolean value?

Body:
I seem to recall that there is a specific term for an accessor method that returns a Boolean value but it escapes me. For example: typical methods such as:

```<code>class Example {
    bool isDirty();
    bool hasChildren();
    bool isValid(SomeType obj);
};
</code>```

I will also settle for such a term as applied to a non-member functions.


答:
If the method is simply returning an attribute of the object, I would call it an accessor, since it is simply used to access a private member variable of the object.

If the method performs some kind of computation or contains logic (beyond the possibility of logging or validation), it's simply a method. It's no different than a method that performs any other operations that use the state of the object and return a value that's not a boolean.

If the method preforms some special task, such as checking equality or validity, I might want to refer to it by what it does, such as calling it a "validator method" or "equality method". Those names is a bit shorter than saying "a method that checks the validity of the object" or "a method that checks the equality of this object against another".

Not everything has a special name, though. Call it by what it is.


问:
How can you effectively use web services in an enterprise environment if you can't use transactions?
The place I'm working at is trying to establish some ground rules, and the debate we're having now is local libraries vs web services for code reuse. Web services seem to be the popular pick in most companies, and that's what most of the developers here are leaning toward.

I just can't see how you can effectively use web services for any serious work. How can I safely execute multiple service calls if I can't use a transaction?

Let's say I have a cron job that grabs customers from our database who meet a certain condition that they need to be notified of. They are sent a fax, an email, and a ticket is created to track the issue internally. That is 3 different service calls that would happen for each customer in a for loop.

If an error occurs anywhere in there, it's possible that, for example, a fax and email is sent to the customer, but a ticket is not created. Or worse, this cron job could contain a bug on that causes it to fail at the same point every time, and it repeatedly emails the same customer. If the libraries were all local, everything could just be wrapped in a transaction, and none of that would happen. But we're using web services in this example.

Note that the email and fax methods actually insert the data into database-backed queue tables, which in turn are handled by a separate cron job process. So the calls to the "send email" and "send fax" service methods could be aborted side-effect free if needed.

An option is to put this entire chunk of code in the web service itself, so the web service itself would call the email, fax, and ticket creating methods in a transaction. But then we're creating a web service method just for the use of a transaction; there is no valid reason we would ever actually need to call this method from anywhere except this one cron script.

How would you generally handle this method?

答:
The way I handled this in a services app I wrote was to create a wrapper to handle the necessary transactions. In my case, the user request, made by web site, desktop app or Windows service, had to query a web service and, based on the result and the user's options, it had to update a local DB and, optionally, a remote one via a web service. Then it had to generate a report to be returned immediately, emailed and/or faxed. I had control over the local DB, email and report generation but none on the web services or fax server.

Creating a wrapper allowed better transaction control and error handling. It also allowed better security by controlling access to internal network services from outside sources. In general, I see the need for transactions and management of the service as a valid reason to create an appropriate wrapper for a single solution as long as code is reused properly (no cut-n-paste coding).


问:
When should an IT consultant use full disc encryption?
In what circumstances should an IT Consultant encrypt their hard drive to protect their code/data of their clients?

I am thinking that if it does not add much to your work load you might as well use full disc encryption with a 'weak' password to at least prevent someone from accessing your email files and other documents if your laptop is stolen, even if they will not get access to any database files or other very sensitive data.

答:
Frankly, I don't think there's any excuse for not using FDE. I have used it in my laptop for years, with practically no issues.

I use LUKS encryption, which is part of Debian (the installer will even set it up for you).

To address the concerns in other answers:

if you forget your password, this means all your data are as good as gone True, but this only means you need to keep your password written down in a safe place (or good memory). Forgetting is not much of an issue, because you have to type it in every time you boot.

the full-disk encryption could make sleep mode/hibernation impractical No problem. Sleep is unaffected, because RAM contents are preserved. Hibernation works out of the box, and hibernates to an encrypted swap partition.

reduces performance This is true, but the impact is minimal in normal operation. It is only noticeable if both I/O and CPU are maxed out. The only situation I notice is during video encoding, and even then the overhead is only about 10%.

any encryption can be cracked Unlikely - if you choose a strong passphrase (i.e. one generated by a program), there is (in the foreseeable future) no way to brute-force it.

In my opinion, a laptop with any kind of even mildly private information should always use FDE. Laptops are too easily lost or stolen.


答: What you are describing is in fact a distributed transaction implementing two-phase commit. Some enterprise messaging platforms include transaction managers to support that kind of thing, but concrete products are platform / language dependent. I don't have concrete experience with such tools, but hope these pointers help.</p>

Title: How can you effectively use web services in an enterprise environment if you can't use transactions?

Body:
The place I'm working at is trying to establish some ground rules, and the debate we're having now is local libraries vs web services for code reuse. Web services seem to be the popular pick in most companies, and that's what most of the developers here are leaning toward.

I just can't see how you can effectively use web services for any serious work. How can I safely execute multiple service calls if I can't use a transaction?

Let's say I have a cron job that grabs customers from our database who meet a certain condition that they need to be notified of. They are sent a fax, an email, and a ticket is created to track the issue internally. That is 3 different service calls that would happen for each customer in a for loop.

If an error occurs anywhere in there, it's possible that, for example, a fax and email is sent to the customer, but a ticket is not created. Or worse, this cron job could contain a bug on that causes it to fail at the same point every time, and it repeatedly emails the same customer. If the libraries were all local, everything could just be wrapped in a transaction, and none of that would happen. But we're using web services in this example.

Note that the email and fax methods actually insert the data into database-backed queue tables, which in turn are handled by a separate cron job process. So the calls to the "send email" and "send fax" service methods could be aborted side-effect free if needed.

An option is to put this entire chunk of code in the web service itself, so the web service itself would call the email, fax, and ticket creating methods in a transaction. But then we're creating a web service method just for the use of a transaction; there is no valid reason we would ever actually need to call this method from anywhere except this one cron script.

How would you generally handle this method?


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
I find technical books too general a category and there is no single method that will work well with all types of books. A lot is also dependent on the interest and appropriate domain knowledge (beyond basic English) that the reader should already possess in order to cover the material efficiently, within a reasonable amount of time. It is important to place the correct expectations, i.e. no normal person should expect to speed read a dictionary from cover to cover and understand much, as there is simply too much depth/content to be digested within a short time as compared to regular text like news or fiction.

Reference books - mostly used for reference, if you really intend to read one from cover to cover, be prepared to possess the background knowledge needed for an acceptable read rate. I find the TAOCP series of books to have a particularly high requirement, and speed reading is not going to work when you need to pause and think after every a few sentences. They are more like textbooks that are best studied when there are exercises to work on.

Tutorials/guides - these are the easiest to read in entirety, especially those with worked examples that can be translated into hands-on activity, which is a more engaging and effective way of verifying the knowledge gained. I do not mind prose, for which speed reading is very effective.

All that being said, it might be more important to identify the right kind of books one should read at any one time, and leave the insurmountable hurdles till later when one is in a better position to handle them.

Title: How do people read big technical books?


答:
The three rules of relational databases:

Normalize

Normalize

Normalize

So your question answers itself. Keep the status inside of it's own table and use GUID/UUIDs as your id. Indexed GUIDS are very fast, and fix the problems intrinsic to incrementing numbers. With an id you can do cool things like ask the DB for all completed posts using the id, and because you are working within the relational db paradigm, it is very fast. If you have just a field, the DB has to loop over every single row and do a text comparison, maybe with munging, and that is very slow.

Post status names can change, more info about post status can go into the table, everything just works if you normalize.

For example, you can add status levels as additional info, which would allow for the comparison ammoQ mentions. But they don't depend upon the key for positioning, allowing rearranging of status level without harming DB integrity. You can also insert additional levels, which is quite a trick if you have the level associated to the autoincrementing key.


问:
Why do they name a program “mogrify” in Imagemagick?
I am not a native English speaker. Is there some trick in this name? What does it mean or imply?

PS. I don't know whether this is the right SE site to post this question but if it is not could you indicate me?

答:
A visual explanation of the origins of the term at AMAT page on Transmogrification seems appropriate:

Changing something into something else the easy way (without much effort and painlessly, of course) is an old dream of everybody...

Here is a present day expression of the need to dream about transmogrification from one of my favorite books dealing about children and how to raise them:
  <img src="https://i.stack.imgur.com/dFzqE.gif" alt="http://www.google.com/imgres?hl=en&sa=X&biw=1918&bih=908&tbm=isch&prmd=imvns&tbnid=AlJIxoOqXZyVoM:&imgrefurl=http://www.tf.uni-kiel.de/matwis/amat/def_en/kap_5/illustr/i5_1_4.html&docid=r5LxPg7TlObFmM&imgurl=http://www.tf.uni-kiel.de/matwis/amat/def_en/kap_5/illustr/transmogrification.gif&w=578&h=603&ei=gX06T7PdA4Ps0gGssfTFCw&zoom=1&iact=rc&dur=406&sig=109570079625149764910&page=1&tbnh=133&tbnw=127&start=0&ndsp=52&ved=1t:429,r:0,s:0&tx=80&ty=52" title="Transmogrification explained - CALVIN AND HOBBES">

Well, a working version of a transmogrifier has not been invented yet. So if you really want to change yourself into a person who knows about defects in crystals, you must still do it the hard way!


问:
Should I avoid private methods if I perform TDD?
I'm just now learning TDD. It's my understanding that private methods are untestable and shouldn't be worried about because the public API will provide enough information for verifying an object's integrity.

I've understood OOP for a while. It's my understanding that private methods make objects more encapsulated, thus more resistant to change and errors. Thus, they should be used by default and only those methods that matter to clients should be made public.

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Also, it's considered bad practice to add methods for the sake of testing.

Does this mean TDD is at odds with encapsulation? What is the appropriate balance? I'm inclined to make most or all of my methods public now...

答:
Of course you can have private methods, and of course you can test them.

Either there is some way to get the private method to run, in which case you can test it that way, or there is no way to get the private to run, in which case: why the heck are you trying to test it, just delete the damn thing!

In your example:

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Why would that be untestable? If the method is invoked in reaction to an event, just have the test feed the object an appropriate event.

It's not about having no private methods, it's about not breaking encapsulation. You can have private methods but you should test them through the public API. If the public API is based on events, then use events.

For the more common case of private helper methods, they can be tested through the public methods that call them. In particular, since you are only allowed to write code to get a failing test to pass and your tests are testing the public API, all new code you write is usually going to be public. Private methods only appear as a result of an Extract Method Refactoring, when they are pulled out of an already existing public method. But in that case, the original test which tests the public method still covers the private method as well, since the public method calls the private method.

So, usually private methods only appear when they are extracted from already tested public methods and are thus already tested as well.


答:
It's my understanding that private methods are untestable

I disagree with that statement, or I would say you don't test private methods directly. A public method may call different private methods. Maybe the author wanted to have "small" methods and extracted some of the code into a cleverly named private method.

Regardless of how the public method is written, your test code should cover all paths. If you discover after your tests that one of the branch statement (if/switch) in one private method has never been covered in your tests, then you have a problem. Either you missed a case and the implementation is correct OR the implementation is wrong, and that branch should never have existed in fact.

That is why I use Cobertura and NCover a lot, to make sure that my public method test also covers private methods. Feel free to write good OO objects with private methods and don't let TDD/Testing go in your way in such matter.

Title: Should I avoid private methods if I perform TDD?

Body:
I'm just now learning TDD. It's my understanding that private methods are untestable and shouldn't be worried about because the public API will provide enough information for verifying an object's integrity.

I've understood OOP for a while. It's my understanding that private methods make objects more encapsulated, thus more resistant to change and errors. Thus, they should be used by default and only those methods that matter to clients should be made public.

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Also, it's considered bad practice to add methods for the sake of testing.

Does this mean TDD is at odds with encapsulation? What is the appropriate balance? I'm inclined to make most or all of my methods public now...


问:
What is the ideal learning path to building Android apps with Scala, without prior Java experience
Unfortunately, there are not currently any books on the subject of 'Learn Android Development with Scala', which would be the ideal solution. I'm guessing that I'll need to pick up at least 3 books here, one for each topic. However, I have no idea what order to read them in, whether to read them simultaneously, what parts of the Java book I can safely skip, etc.

What is the best path for me to get started building Android apps using Scala?

答:
You have not stated the reason why you prefer Scala over Java to program android apps.

You need to have a solid foundation in OOP. Also have you looked on Google Code for programming on Scala in Android: http://code.google.com/p/scala-android/ . Also look into this as well: http://www.assembla.com/wiki/show/scala-ide/Developing_for_Android


答:
Well, it's possible for me to make an object that has only private
  methods and interacts with other objects by listening to their events.
  This would be very encapsulated, but completely untestable.

How does this object react to those events? Presumably, it must invoke methods on other objects. You can test it by checking whether those methods get called. Have it call a mock object and then you can easily assert that it does what you expect.

The issue is that we only want to test the object's interaction with other objects. We don't care what's going on inside an object. So no, you shouldn't have any more public methods then before.


答:
Your example is still perfectly testable as long as you use Dependency Injection to provide the instances that your CUT interacts with. Then you can use a mock, generate the events of interest, and then observe whether or not the CUT takes the correct actions on its dependencies.

On the other hand, if you have language with good event support you may take a slightly different path. I don't like when objects subscribe to events themselves, instead have the factory that creates the object wire up events to the public methods of the object. It's easier to test, and makes it externally visible what kinds of events the CUT needs to be tested for.


答:
When you create a new class in your code, you do it to answer some requirements. The requirements say what the code must do, not how. This makes it easy to understand why most testing happens at public methods level.

Through tests, we verify that the code does what it is expected to do, throws appropriate exceptions when expected, etc. We don't really care how the code is implemented by the developer. While we don't care about implementation, i.e. how the code does what it does, it makes sense to avoid testing private methods.

As for testing classes which don't have any public methods and interact with the outside world only through events, you can test this too by sending, through tests, the events and listening to the response. For example if a class must save a log file each time it receives an event, the unit test will send the event and verify that the log file is written.

Last but not least, in some cases it is perfectly valid to test private methods. That's why for example in .NET, you can test not only public, but also private classes, even if the solution is not as straightforward as for public methods.


答:
A few private methods usually aren't an issue.  You just test them through the public API as if the code were inlined into your public methods.  An excess of private methods may be a sign of poor cohesion.  Your class should have one cohesive responsibility, and often people make methods private to give the appearance of cohesiveness where none really exists.

For example, you might have an event handler that makes a lot of database calls in response to those events.  Since it's obviously bad practice to instantiate an event handler to make database calls, the temptation is to make all the database-related calls private methods, when they should really be pulled out into a separate class.


问:
How do programmers quit a job?
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.

答:
Write a letter.  It doesn't need to be long, and should not go into details of why you're unhappy (if in fact you are).  "I am resigning effective (current date plus two weeks) in order to pursue other opportunities".  Be nice, even if you have to lie - something to the effect of "I am grateful for the opportunities which have been afforded me at (current place of employment), but feel that my career goals will best be met elsewhere".  DO NOT SAY "Everyone at this company is a total waste of oxygen, I hate you all, and the bomb goes off in ten minutes!" - this will only cause hard feelings.  It should be hand delivered, hard-copy and in person.  Doesn't have to be in an envelope, etc, but resigning by email or phone is IMO tacky and gutless if you work in the same office.  (I've resigned over the phone before, but A) I didn't work in the same location as my boss, B) we had a good relationship anyways, and C) it was a contracting firm so resignations were pretty common).

Do not tell them where you are going, especially if you feel they may be vindictive.  You are under no obligation to do so.

Two weeks notice is customary in order to wrap up current tasks.  However, don't be surprised if they show you the door immediately.

Do not accept a counter-offer unless your principle reason for leaving is low pay, in which case the counter would have to be significantly more than the place you plan to go to.

Do not delete business-related emails or documents - these are the property of the business.  Stuff from your mom, girlfriend, etc, should be deleted BEFORE you turn in your notice (because they may cut off your computer access and pitch you out the door immediately - hey, it happens).

Turn your notice in to your boss.  Don't tell him you hate his stinking guts and hope he rots in hell, even in you do - burnt bridges never helped anyone.  If you think your boss may be vindictive or lie you might want to blind-copy your boss's boss on your resignation letter - this is about the ONLY time I would ever BCC anybody.

Remember the military maxim - "Seize and hold the high ground" - at least then they have to actively lie to say bad things about you.  Be polite, nice, and "let them down easy".  It may help to say something like "I'm sure we'll remain friends" even if you hope to never see them again.  Words like "I've learned a lot here" can help, as can "I will always respect the integrity of this firm", even if they're a bunch of despicable, lying bastards who would sell their own children for pocket change.

Good luck, and have fun at your new job.

Title: How do programmers quit a job?


问:
How do I use PowerMock / Mockito / EasyMock to use a mocked object for dependency injection?
I have an AuthenticationManager.authenticate(username,password) method that gets called in someMethod of a SomeService under test. The AuthenticationManager is injected into SomeService:

```<code>@Component
public class SomeService {
    @Inject
    private AuthenticationManager authenticationManager;

    public void someMethod() {
        authenticationManager.authenticate(username, password);
        // do more stuff that I want to test
    }
}
</code>```

Now for the unit test I need the authenticate method to just pretend it worked correctly, in my case do nothing, so I can test if the method itself does the expected work (Authentication is tested elsewhere according to the unit testing principles, however authenticate needs to be called inside that method)

So I am thinking, I need SomeService to use a mocked AuthenticationManager that will just return and do nothing else when authenticate() gets called by someMethod(). How do I do that with PowerMock (or EasyMock / Mockito, which are part of PowerMock)?

Or is there another way to tell Spring to use some Mock instead of the real deal, when injeeting the AuthenticationManager into SomeService?

Or is my design wrong?

Thanks!

Edit - found a solution, would like to hear comments

So I found a nice way to inject a mock without having to use a setter or package level:

```<code>@RunWith(PowerMockRunner.class)
public class TestOrderService {

    @Mock
    private AuthenticationManager authenticationManager;

    @InjectMocks
    private OrderService orderService = new OrderService();

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        Mockito.doNothing().when(this.authenticationManager).authenticate(null, null);
    }

    @Test
    public void testOrderService() {
        orderService.save(null, null, null);
    }
}
</code>```

with OrderService like this:

```<code>public void save(String username, Order order) {
    authenticationManager.authenticate(username, password);
    // do something with the order...
}
</code>```

Now the save method will call authenticate on the mock and the mock does nothing leaving me free to test the actual work inside my service method (which actually is calling a manager method but that was not the point ;) )

答:
I personally don't use spring on the unit testing side (except maybe a single test to verify that the application context loads properly). Instead I use setter methods to manually wire the mocks (actually I use project lombok's @Setter annotation), OR if I'm using @Autowired I make the member variables package scoped so the unit test can directly set the values.

I don't see how you're going to get things like Mockito to work via dependency injection, because you'll always be new-ing your object inside the unit test and then creating mock behaviors for the methods. Also, you don't lose much by doing it this way, because you'll only need to setup direct dependencies of the class under test (because they're mocks), which is much easier than what spring DI does, which is recursive dependency creation and wiring on real objects.


问:
Using a column to store the company or a separate database?
I am writing an system for the company to put their promotion material on the site, which is like some kinds of CMS. So, I need a database that store their data, but I am considering how to store their data.... First approach is use a single table to store their data, but use a column, like 'company_code' to distinguish the company, another approach is create a separate database for a company....

(Of course, will check the company_code or company table name is existed or not, if yes, will assign a new company_code or company table name by programme.)

So, which approach is better? Thanks.....

答:
I'm not sure there's enough info here to answer properly... Are you planning to store data for multiple companies in this system?

The way I would do it (based on the info herE) is  give them their own database (I'm assuming here that your "database" has multiple tables per customer and that they could be hosted on the customer's server). If other customers want the same system, they would get their own database too. Changes/upgrades to the data structures would be carefully deployed to all customer databases via SQL scripts, after careful testing and pre-upgrade back-ups, of course!

On the other hand, if you're only storing a little bit of data for each customer for your system to make use of, then it might make sense to store all companies in a single table.

You might have to describe this problem a little bit better for a clearer answer.


答:
Does this mean TDD is at odds with encapsulation? What is the
  appropriate balance? I'm inclined to make most or all of my methods
  public now.

TDD is not at odds with encapsulation.  Take the simplest example of a getter method or property, depending on your language of choice.  Let's say that I have a Customer object and I want it to have an Id field.  The first test I'm going to write is one that says something like "customer_id_initializes_to_zero".  I define the getter to throw a not implemented exception and watch the test fail.  Then, the simplest thing I can do to make that test pass is have the getter return zero.

From there, I go onto other tests, presumably ones that involve the customer ID being an actual, functional field.  At some point, I probably have to create a private field that the customer class uses to keep track of what should be returned by the getter.  How exactly do I keep track of this?  Is it a simple backing int?  Do I keep track of a string and then convert it to int?  Do I keep track of 20 ints and average them?  The outside world doesn't care - and your TDD tests don't care.  That is an encapsulated detail.

I think this is not always immediately obvious when starting TDD -- you're not testing what methods do internally - you're testing less granular concerns of the class.  So, you're not looking to test that method DoSomethingToFoo() instantiates a Bar, calls a method on it, adds two to one of its properties, etc.  You're testing that after you mutate the state of your object, some state accessor has changed (or not).  That's the general pattern of your tests: "when I do X to my class under test, I can subsequently observe Y".  How it gets to Y is none of the tests' concern, and this is what is encapsulated and this is why TDD is not at odds with encapsulation.


问:
Real world implementation of functional programming?
I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language.

Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc.

Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?

答:
Heres a list of Common Lisp success stories:

http://wiki.alu.org/Industry%20Application

http://www.franz.com/success/

http://www.lispworks.com/success-stories/index.html

Although Common Lisp is only partly functional(it also supports OOP and procedural, as well as anything you wish to implement your self, or with a library), it's a very pragmatic language, and extremely powerful in the hands of a competent programmer. I actually use it to write web apps with the excellent RESTAS framework.

And the commercial python project that I'm working on right now will eventually be supplemented by services written in lisp(RESTAS as suggested by its name is excellent for RESTful services).


答:
Having a database per company isn't really a scalable or maintainable solution.  Unless you know that there will only be a couple companies involved, I'd recommend avoiding it.

Relating a Company (via company_code) to each table containing company-specific data is a reliable solution that has worked for me numerous times in the past.  It's relational, maintainable, scalable, and it makes it simpler to do cross-company queries for metrics and the like.  It's the way to go.

Title: Using a column to store the company or a separate database?

Body:
I am writing an system for the company to put their promotion material on the site, which is like some kinds of CMS. So, I need a database that store their data, but I am considering how to store their data.... First approach is use a single table to store their data, but use a column, like 'company_code' to distinguish the company, another approach is create a separate database for a company....

(Of course, will check the company_code or company table name is existed or not, if yes, will assign a new company_code or company table name by programme.)

So, which approach is better? Thanks.....


答:
Prefer testing to the interface over testing on the implementation.

It's my understanding that private methods are untestable

This depends on your development environment, see below.

[private methods] shouldn't be worried about because the public API will provide enough information for verifying an object's integrity.

That's right, TDD focuses on testing the interface.

Private methods are an implementation detail that could change during any re-factor cycle. It should be possible to re-factor without changing the interface or the black-box behaviour. In fact, that is part of the benefit of TDD, the ease with which you can generate the confidence that changes internal to a class will not affect users of that class.

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Even if the class has no public methods, it's event handlers are it's public interface, and it its against that public interface that you can test.

Since the events are the interface then it is the events that you will need to generate to test that object.

Look into using mock objects as the glue for your test system. It should be possible to create a simple mock object that generates an event and picks up the resultant change of state (possible by another receiver mock object).

Also, it's considered bad practice to add methods for the sake of testing.

Absolutely, you should be very wary of exposing internal state.

Does this mean TDD is at odds with encapsulation? What is the appropriate balance?

Absolutely not.

TDD shouldn't change the implementation of your classes other than to perhaps simplify them (by applying YAGNI from an earlier point).

Best practice with TDD is identical to best practice without TDD, you just find out why sooner, because you are using the interface as you are developing it.

I'm inclined to make most or all of my methods public now...

This would be rather throwing the baby out with the bath water.

You shouldn't need to make all methods public so that you can develop in a TDD way. See my notes below to see if your private methods really are untestable.

A more detailed look at testing private methods

If you absolutely must unit test some private behaviour of a class, depending on the language/environment, you may have three options:

Put the tests in the class you want to test.

Put the tests in another class/source file & expose the private methods you want to test as public methods.

Use a testing environment that allows you to keep test and production code separate, yet still allow testing code access to private methods of the production code.

Obviously the 3rd option is by far the best.

1) Put the tests in the class you want to test (not ideal)

Storing test cases in the same class/source file as the production code under test is the simplest option. But without a lot of pre-processor directives or annotations you will end up with your test code bloating your production code unnecessarily, and depending on how you have structured your code, you may end up accidentally exposing internal implementation to users of that code.

2) Expose the private methods you want to test as public or protected methods (really not a good idea)

As suggested this is very poor practice, destroys encapsulation and will expose internal implementation to users of the code.

3) Use a better testing environment (best option, if it is available)

In the Eclipse world, 3. can be achieved by using fragments. In the C# world, we might use partial classes. Other languages/environments often have similar functionality, you just need to find it.

Blindly assuming 1. or 2. are the only options would be likely to result in production software bloated with test code or nasty class interfaces that wash their dirty linen in public. *8')

All in all - it is much better not to test against private implementation though.

ContentLicense: CC BY-SA 4.0


问:
How can I explain the difference between NULL and zero?
Working on a problem that uses the percent change formula:

```<code>percent change =  100 * [(new value - old value) / old value]
</code>```

How would I explain the difference if new value or old value = NULL, rather than 0 to someone who might not be a programmer?

My boss is wondering why there is an empty string in the TextBox rather than a value, because we have the old value, but not the new value.

答:
NULL is the absence of a value.

-Zero- is a value, and that value is -Zero-.

If I had to explain these concepts to somebody, I would draw two boxes.

An empty box would represent NULL.

A box with a number -Zero- in it would represent -Zero-.


问:
Programming "everything" using HTML5?
HTML 5 applications in the browser really seem to be taking off. I've been using src:kit within Google Chrome for a few weeks and love it. I'm an ASP.Net (C#/MVC 3) developer by trade, and in the past did several pieces of WebForms programming.

With Windows 8 app development moving into the trade of local HTML5 apps, and the major smartphone browsers supporting HTML5 installation, as well as many platforms supporting it (PhoneGap and Titanium, for example), are we already/will we soon be at the point that I could create an app that would be fully "installable" to run as a standalone on every platform?

I do realise that a database (or instert-your-data-store-here) would also be necessary, so adding another language in there for middleware would be necessary. C# on Mac/Linux with Mono is possible, but Mono generally only creates a GTK+ Application, so I would likely need to create another wrapper to house the application... I think.

Any suggestions of a better language to use as middleware? I.e. for ease of transportation - I've got far more experience with C# than anything else so would like something from that family if I'll need to do something different.

Basically, how far away are we from this? What still needs to change? Most importantly, if it is possible (which I believe, theoretically it is), what is the big jump between where we are now and when we will be there?

This will eventually turn into a program, so it is a completely practical problem that I'm working my way through (I'll start development after Christmas).

EDIT: To clarify, by 'every' platform, I include at least the following: Windows XP+/Mac OS X/Linux: any distro pretty much in the last 2 years/iOS/Android/Blackberry 5+/Windows Phone 7+

答:
My theory, despite I'm not so much of a master of programming, is that if HTML5 could do everything we would have no need of other languages and most likely we would dispose of them. There are programmers out there which are specialists in multiple languages including HTML5, and yet they write software in Python, Java, C++ etc.

HTML5 has huge advantages, and indeed anything can be done, but the real question here should be if it can get anything done correctly and accurately. For example a Java game would probably be inferior to a C++ version of the same game  due to it's dependencies and Java factors.

There are more supreme programming languages out there, C++ has huge capabilities with little dependencies, and after all, this same question you're asking could've probably been asked 10-20 years ago but with another programming languages, but in the meantime, more were invented.

I think the real answer here is that we'll have to wait, perhaps in a couple of years a new programming language will be created, a superior one which will be cross-platform and usable in any domain and for everything computer-related.

Title: Programming "everything" using HTML5?


问:
Is it OK to introduce methods that are used only during unit tests?
Recently I was TDDing a factory method. The method was to create either a plain object, or an object wrapped in a decorator. The decorated object could be of one of several types all extending StrategyClass.

In my test I wanted to check, if the class of returned object is as expected. That's easy when plain object os returned, but what to do when it's wrapped within a decorator?

I code in PHP so I could use ext/Reflection to find out a class of wrapped object, but it seemed to me to be overcomplicating things, and somewhat agains rules of TDD.

Instead I decided to introduce getClassName() that would return object's class name when called from StrategyClass. When called from the decorator however, it would return the value returned by the same method in decorated object.

Some code to make it more clear:

```<code>interface StrategyInterface {
  public function getClassName();
}

abstract class StrategyClass implements StrategyInterface {
  public function getClassName() {
    return \get_class($this);
  }
}

abstract class StrategyDecorator implements StrategyInterface {

  private $decorated;

  public function __construct(StrategyClass $decorated) {
    $this->decorated = $decorated;
  }

  public function getClassName() {
    return $this->decorated->getClassName();
  }

}
</code>```

And a PHPUnit test

```<code> /**
   * @dataProvider providerForTestGetStrategy
   * @param array $arguments
   * @param string $expected
   */
  public function testGetStrategy($arguments, $expected) {

    $this->assertEquals(
      __NAMESPACE__.'\\'.$expected,
      $this->object->getStrategy($arguments)->getClassName()
    )
  }

//below there's another test to check if proper decorator is being used
</code>```

My point here is: is it OK to introduce such methods, that have no other use than to make unit tests easier? Somehow it doesn't feel right to me.

答:
I'm an absolute TDD newbie, but it seems to depend on the method being added. From what I understand of TDD, your tests are supposed to "drive" the creation of your API to some degree.

When it's OK:

As long as the method doesn't break encapsulation and serves a purpose that's in line with the object's responsibility.

When it's not OK:

If the method seems like something that would never be useful, or doesn't make sense in relation to other interface methods, it may be incohesive or confusing. At that point, it would muddy my understanding of that object.

Jeremy's example, "...when you need to know how efficient some routine is, for example does your Hashmap use an evenly distributed range of hash values - nothing in the external interface would be able to tell you that."


问:
Software testing for developer
I'm a software developer. What do I need to know about software testing (apart from TDD, unit-testing and stuff) to make my software work as it should? For example, there are cases when TDD is not applicable. Therefore, I need to do simple smoke testing of my code every time it is deployed/changed. In order to prevent silly mistakes, I probably should have some simple test cases and check manually if everything works properly. It's better to avoid bugs than fix them, right? And this is the time when basic software testing skills might come in handy. What are those basics that I need to know?</p>

答:
Well, first off, for avoiding 'silly' mistakes, you can generally employ static analysis tools.  This will help you catch things like failing to meet coding convetions, possible null dereferences, etc.  I would say that's a first line of defense to writing quality software.

Your second line of defense is your unit tests, which provide rapid feedback that your code does what it is supposed to and continues to do so as it's changed.

From there, you have the concept of integration/behavior tests that test whether or not the code actually fulfills your requirements.  These are going to be your "smoke tests" that exercise your application in a more integrated state.  I cannot overemphasize that I believe you ought to automate these.  Firing up an application and clicking around randomly to get things to break (i.e. a "bug bash") is not productive use of a skilled developer's time, in my opinion.  You can always automate (that's what we do for a living).  There are GUI exercise tools if need be - you can test all the layers below the GUI as well.  You can do load tests, you can do long running tests, you can randomize things and log execution steps, etc.

So, in the end, I'd say that the software testing skill that you need is how to automate tests of integrated parts of your code, and how to interpret the results of that automation.  These sorts of repeatable, documentable testing efforts will be a lot more valuable to you than "try to break it" (not that this is a bad thing to do -- just not optimal for a developer to do it).

Title: Software testing for developer


问:
How to store record statuses (like pending, complete, draft, cancelled...)
Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example.

I have a simple Blog application and each post has a status one of: published, draft or pending.

The way i see it there are 2 ways to model this in the database.

The Post table has a text field that includes the status text.

The Post table has a status field that contains the ID of a record in the PostStatus table

The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed.

Can anyone explain the advantages/disadvantages of each?

Cheers!

My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases

答:
I'd like to add to the otherwise insightful answers that for full normalization, a change in the status of an entity is actually modeled in a separate entity, e.g. named 'statusChange'.

You'd need an extra join with the statusChange entity, but you win the possibility of adding extra information, such as the actor performing the change, possible comments on why the change occurred and a date at which the statusChange is performed and possibly even when it becomes effective.


答:
The keywords you are looking for are 'web service choreography'.

Check out Wikipedia's article about it.


答: The difference between 0 and null is like the difference between having a bank account with a 0 balance and not having a bank account at all.</p>

Title: How can I explain the difference between NULL and zero?

Body:
Working on a problem that uses the percent change formula:

```<code>percent change =  100 * [(new value - old value) / old value]
</code>```

How would I explain the difference if new value or old value = NULL, rather than 0 to someone who might not be a programmer?

My boss is wondering why there is an empty string in the TextBox rather than a value, because we have the old value, but not the new value.


答:
It's interesting that as I'm participating in this particular Q&A, there is a similar thread about services supporting multiple platforms on the DDD/CQRS mailing list that I'm participating in. I can re-iterate some of my advice here.

One option for supporting transactions in a heterogeneous environment is using a transport mechanism that supports transactions and is supported on all platforms from which it will be used. The Advanced Message Queue Protocol (AMQP) does support transactions and there is a native API for almost every language that is commonly used today. RabbitMQ is a server that implements AMQP and has been vetted in the industry as a robust solution.

Leveraging a RabbitMQ based system puts you on a path to having a full ESB should you need to grow into it. You publish messages to a channel and subscribe to a queue. Where that gets really powerful is that between the channel and queue, you can perform a lot of interesting things. A channel can feed multiple queues (pub/sub) a queue can be fed by multiple channels, you can route messages to different queues based on content, etc. etc.

I was just reading about alternatives to transactions (which come with overhead and turn an async operation into a blocking op). RabbitMQ supports what's called a publisher confirm. Basically it allows you to register a callback for a published method to handle a failed transaction. In your case it could undo the email/fax requests and delete the ticket.

Of course the rabbit hole (pardon the pun) goes even deeper from there. You can use Rabbit to do complex orchestrations with both internal and external web services.

For your public facing webservices, it becomes dead simple. Your service (be it SOAP, REST, or JSON) just publishes a message to the appropriate service queue and let your internal system handle it from there.

There's also functionality for creating a request/response message for those scenarios where you expect information back quickly.


答:
I just can't see how you can effectively use web services for any serious work. How can I safely execute multiple service calls if I can't use a transaction?

You can't.

The question you should be asking is: how do I implement transactions with web service framework X? Right now, you're just assuming that it's impossible.


答: I've struggled with this same issue as well.  Really, the way to get around it is this: How do you expect the rest of your program to interface with that class?  Test your class accordingly.  This will force you to design your class based on how the rest of the program interfaces with it and will, in fact, encourage encapsulation and good design of your class.


答:
The most useful skill I have ever encountered in a developer/tester is the ability to "forget" all assumptions about how the user is supposed to use the software. I won't say "dumb it down", because testers have to be very intelligent about their job, but a developer testing their own work must abandon any pre-conceived notions of how they envisioned the end user interacting with it.

For instance, I know a tester whose first action when opening any sort of "record maintenance" screen is to immediately hit "save". Your average developer might think that behavior is so ridiculous that they don't build in appropriate error-checking for a case where NOTHING was specified by the user. Navigation testing is another usual soft spot, especially in web apps; does your website react properly to the "Back" button? Many, in fact, do not, especially if they rely heavily on ViewState and postbacks.

A good tester realizes that nothing can be assumed as to the behavior of the end user. These are the testers that developers hate, because they'll come back with some edge case that is a pain and two-thirds to cover. But, they're also the testers that help you produce rock-solid-reliable software. After a little while, you as a developer, submitting release candidates to a tester such as this, will begin to adopt some of the same mindset, writing automated tests for edge cases and incorporating "stupid" user actions into manual UI and end-to-end testing.

One thing; TDD is almost never "not applicable"; the only time you shouldn't TDD something is when there isn't a suitable testing framework for you to use, and that would only be a valid reason for a very small set of "legacy" or "specialty" languages.

Title: Software testing for developer

Body: I'm a software developer. What do I need to know about software testing (apart from TDD, unit-testing and stuff) to make my software work as it should? For example, there are cases when TDD is not applicable. Therefore, I need to do simple smoke testing of my code every time it is deployed/changed. In order to prevent silly mistakes, I probably should have some simple test cases and check manually if everything works properly. It's better to avoid bugs than fix them, right? And this is the time when basic software testing skills might come in handy. What are those basics that I need to know?</p>


答: A book that was recommended to me and which I relied on as a professional software tester is Testing Computer Software by Kaner, Falk, and Nguyen. Topics include the fact that you simply can't test everything, how to report and analyze bugs (more useful for a larger team or when dealing with bug reports from customers), equivalence classes and boundary values, localization, user manuals, legal consequences, and managing. So it covers a broad range of areas relevant to testing, and introduces and defines key terminology. If you're going to spend a lot of time testing or even working with testers, I recommend this book.

Title: Software testing for developer


问:
Is it possible to use C++ with the .NET framework?
I've read many comments about GUI programming, in both, C# and C++. And I noticed that Microsoft's .NET framework is powerful for GUI programming. So is it possible to use C++ and .NET framework?

I think it will be a great combination since C++ is powerful language, and .NET framework is preferred for GUI programming on Windows, as I've read. Is it possible to write the GUI in C# and the functionality in C++?

答: Not really. There is a hybrid language C++/CLI, but it's only good for interoperation (Microsoft's official policy). Because of the way the .NET framework is designed, there are many language semantics which really don't fit running on the CLR, and C++ exhibits many of them.</p>


答:
Storing the status as an index into another table is an unnecessary complication.  Store the status directly in the table in a readable way.  In the application code use constants or an enumeration type.  This will result in simpler application code and ease debugging of the data layer.

This does not denormalize the data, it merely changes the representation.  If the database supports enumerations directly, then use that.  Otherwise use a constraint to restrict the column values.  You are going to have a constraint either way: either a direct constraint on the column values, or a foreign key constraint.

Yes, you may have to present the status differently to different users.  That is a presentation problem, to be solved in the presentation layer, not the persistence layer.


问:
In which format should I sent the values in database in PHP?
I am developing an application which is based on the quiz contest for competetive exams. The user can give different categories of tests, which will contain different types of questions of following types:

Single select,

Multiple select,

Match making,

Comprehension (the quetion will be a paragraph and on the basis of that there will be questions),

Free text (the user will have to type the answer),

Range (the user have to select a number from 1 to 10).

My concern is that while creating questions from admin site, how can I manage the database for above type of questions?

I have one answer column in the question table but there are six type of questions so what should be the convenient way for saving answers in the databse so that when user will give answer, I can easily check if the answer matches?

I am thinking of saving the answer in the form of XML tags. Will this be a good approach?

答:
You will probably have an answers table. This table should have a question_id so you know what question is being answered, and it should also help you figure out what kind of data is in the answer, assuming that the questions table has some sort of question_type_id that refers to one of the question types above.

Then, the simplest (IMO) solution: For most of these answer types, you could have a single text field to store the answer, probably no longer than the max length you'd allow for Free Text answers (assuming no more than a hundred characters or so). For the longer answers for the Comprehension type, you may want a separate table, call it large_answers, for holding very large text objects and store the answer there, and in your main answers table refer to the large_answers by an optional large_answer_id field.

I'm not sure why XML would be needed for this.

So:

```
Questions
  question_id (unique key)
  question_type_id
  (other fields that don't have an impact on this solution)</p>

<p>Answers
  Answer_id (unique key)
  question_id (refers to questions.question_id)
  answer_text (non-null, but for large_answers, maybe just store the first n characters, as a preview)
  large_answer_id (optional, refers to large_answers.large_answer_id)</p>

<p>large answers
  large_answer_id (unique key)
  large_answer_text (CLOB type)
</Pre></p>

<p>Or you could do it like this:</p>

<p>```
Questions
  (as before)

Answers
  Answer_id (unique key)
  question_id (refers to questions.question_id)
  answer_text (nullable)

large answers
  large_answer_id (unique key)
  answer_id (refers to answers.answer_id)
  large_answer_text (CLOB type, non-null)

In the above schema, you'd have the large_answers referring back to the answer they are associated with, instead of the answers having a nullable reference to a large_answer. Hmmm the more I think about it the more I like the second schema as I don't like the idea of a nullable large_answer_id, but I'm sure there's good arguments to be made for both sides... ;)

Body:
You will probably have an answers table. This table should have a question_id so you know what question is being answered, and it should also help you figure out what kind of data is in the answer, assuming that the questions table has some sort of question_type_id that refers to one of the question types above.

Then, the simplest (IMO) solution: For most of these answer types, you could have a single text field to store the answer, probably no longer than the max length you'd allow for Free Text answers (assuming no more than a hundred characters or so). For the longer answers for the Comprehension type, you may want a separate table, call it large_answers, for holding very large text objects and store the answer there, and in your main answers table refer to the large_answers by an optional large_answer_id field.

I'm not sure why XML would be needed for this.

So:

Questions
  question_id (unique key)
  question_type_id
  (other fields that don't have an impact on this solution)

Answers
  Answer_id (unique key)
  question_id (refers to questions.question_id)
  answer_text (non-null, but for large_answers, maybe just store the first n characters, as a preview)
  large_answer_id (optional, refers to large_answers.large_answer_id)

large answers
  large_answer_id (unique key)
  large_answer_text (CLOB type)

Or you could do it like this:

Questions
  (as before)

Answers
  Answer_id (unique key)
  question_id (refers to questions.question_id)
  answer_text (nullable)

large answers
  large_answer_id (unique key)
  answer_id (refers to answers.answer_id)
  large_answer_text (CLOB type, non-null)

In the above schema, you'd have the large_answers referring back to the answer they are associated with, instead of the answers having a nullable reference to a large_answer. Hmmm the more I think about it the more I like the second schema as I don't like the idea of a nullable large_answer_id, but I'm sure there's good arguments to be made for both sides... ;)


答:
Every type of question will have to be managed differently in your application and will use a different selection of data, it would be best to create multiple tables for each part of the question with that are all related to a central question table, rather than try to have one massive table.

you will want at a minimum a question table, a MC option table, a table for reading selections, a table to store rules on how to grade free text answers; or a table with enough columns for all that.

Title: In which format should I sent the values in database in PHP?

Body:
I am developing an application which is based on the quiz contest for competetive exams. The user can give different categories of tests, which will contain different types of questions of following types:

Single select,

Multiple select,

Match making,

Comprehension (the quetion will be a paragraph and on the basis of that there will be questions),

Free text (the user will have to type the answer),

Range (the user have to select a number from 1 to 10).

My concern is that while creating questions from admin site, how can I manage the database for above type of questions?

I have one answer column in the question table but there are six type of questions so what should be the convenient way for saving answers in the databse so that when user will give answer, I can easily check if the answer matches?

I am thinking of saving the answer in the form of XML tags. Will this be a good approach?


答: Yes, it's formerly known as Managed C++ and now C++/CLI. You have access to the entirety of the .NET Framework (GUI: WinForms, GDI+, etc.) as you would from the other three bundled managed languages, C#, F# and VB.NET.</p>

Title: Is it possible to use C++ with the .NET framework?

Body:
I've read many comments about GUI programming, in both, C# and C++. And I noticed that Microsoft's .NET framework is powerful for GUI programming. So is it possible to use C++ and .NET framework?

I think it will be a great combination since C++ is powerful language, and .NET framework is preferred for GUI programming on Windows, as I've read. Is it possible to write the GUI in C# and the functionality in C++?


答: Instead of private use default modifier. Then you can test those methods individually, not just coupled with public methods. This requires that your tests have the same package structure as your main code.</p>


答:
Depends on the purpose of the database design.

If you design the database simply to support the application (ie the objects (code) are master of all) then using an enumeration (or a psuedo enumeration for classes that don't support them) and storing off the name of the enum is a good idea because you still control the values allowed through the enum and you also make the table a bit easier to read when you are forced to view the raw data (which isn't that often if the code actually rules all). But if the enumeration is flagged. Then I usually store off the enum value (integer).


答:
Some great discussion on analogies to explain the mechanical aspects of a null symbol compared with other values; however, the crux of this question perhaps from the manager's perspective in adequately expressing the results in the UI, representing the meaningful limits of the perecnt changed formula as applied to their specific problem, can be answered more specifically I believe.

In the case of the percentage changed forumula, two things need to be represented: when something is first measured, and when nothing is measured for a particular aspect.

When something is first measured (oldValue === NULL), the percentage change is not applicible; and could/should explicitly be noted that it is the initial measurement for that measurement cycle.

When nothing is measured (newValue === NULL), the actual resulting percent change is actually the value of zero (assuming non-null in the previous cycle).  Zero is generally the appropriate answer to the formula in this case.  There was no measurement in this most recent cycle, and thus no measured change.  That should not imply it did not change, just that nothing was measured, recorded, or communicated in regards to that aspect.


问:
Documenting and enforcing programming standards and guidelines for shared library
Myself and another developer with the go ahead from our IT director have started a general purpose library in .NET with the intention that it will provide many common purpose classes that we use in our day to day development.

During discussions and design of the library we have come up with a set of standards that we want the library to follow to ensure it is maintained and expanded on in a consistent manner.

What is the best way to ensure these decisions we made for the library get feed to the other developers who might be using and adding to this library in the future.  One of our decisions was to ensure we review all checked in code so we expect initially there to be some differences in coding styles of individuals not fitting in with the project standards.

Some ideas I had were:

Add a Read-me.txt to the project that outline the guidelines and standards

Send an email out to everyone in the team to let them know about the project etc

Call a team meeting to go through this new project and our expectations and standards we were aiming to follow

Try and enforce the standards via Visual Studio (not sure if this would be possible or how just an idea)

At the moment there is no general company programming standards so this would be a first really insofar as we are creating a standard that different project teams would need to adhere to.

答:
Generally best to enforce standards using tools like FXCop/Visual Studio static analyser and StyleCop.

StyleCop is an open source static code analysis tool from Microsoft that checks C# code for conformance to StyleCop's recommended coding styles and a subset of Microsoft's .NET Framework Design Guidelines. StyleCop analyzes the source code, allowing it to enforce a different set of rules from FxCop (which, instead of source code, checks .NET managed code assemblies). The rules are classified into the following categories:

Documentation

Layout

Maintainability

Naming

Ordering

Readability

Spacing

StyleCop includes both GUI and command line versions of the tool. It is possible to create new rules to be used.

StyleCop was re-released as an open source project in April 2010...


问:
Best way to handle class relationship
Take a User class and the idea that a User is to be profiled. I see four ways to handle this:

Write the code for the profile into the User class. I am dismissing this right away.

Create a Profile class and make it a property of the User class.

Write a User class (with the boiler-plate name, address stuff), write a Profile class,
and write a UserProfile class - UserProfile is the union of User and Profile.

Write a User class and a Profile class that each have an ID property and let the ID act
as the intersection. This way the User and Profile are independent and another class,
possibly an abstract class with nothing but static methods handles the logic that
describes the connection.

Choices 3 and 4 each require at least three classes. For this case, which is the best choice? If possible to generalize this, would it generally be better to use one of these possibilities?

答:
I'll assume that you are only storing profiles for users.

This is an easy decision. The user has a "has a" relationship to the profile and thus the profile should be encapsulated in its own class and exposed as a component of the User class (e.g. a property). So your second approach is the cleanest one.

Option 1 violates the single responsibility principle. This is only an option if there's very few data collected in profiles and almost not behaviour at all.

Option 2 is the way to go.

Option 3 is too complex. Also violates the single responsibility principle.

Option 4 just sounds like a horrible design. It'll be error prone and not really object oriented. Why would you want to intersect them via ID? That is built on a side effect entirely (namely matching ID of profile and user). You'll need some sort of reference from user to profile anyway. So why not have that reference in a property and let an ORM map it (see Option 2)?

It would be most useful to capture ther more abstract case of such a
  profile than the specifics of a financial protfolio - or so it seems
  to me. The doctor and the financial advisor both need your personal
  data (profile) to have the best chance to do the right thing.

You can always extend from a Profile-BaseClass and store it in the User-Aggregate. And if you don't want to be implementation dependent, create a basic interface for everything that you need from the all cases of profiles that you can imagine.

Title: Best way to handle class relationship


答:
Use FxCop and StyleCop to analyze and enforce rules that describe the coding standard you expect for your library. You could also write up a document that explains your coding standard, but using code analysis is the best way to actual enforce them.

Edit:

See this question for more information about the code analysis available in certain versions of Visual Studio.

Title: Documenting and enforcing programming standards and guidelines for shared library

Body:
Myself and another developer with the go ahead from our IT director have started a general purpose library in .NET with the intention that it will provide many common purpose classes that we use in our day to day development.

During discussions and design of the library we have come up with a set of standards that we want the library to follow to ensure it is maintained and expanded on in a consistent manner.

What is the best way to ensure these decisions we made for the library get feed to the other developers who might be using and adding to this library in the future.  One of our decisions was to ensure we review all checked in code so we expect initially there to be some differences in coding styles of individuals not fitting in with the project standards.

Some ideas I had were:

Add a Read-me.txt to the project that outline the guidelines and standards

Send an email out to everyone in the team to let them know about the project etc

Call a team meeting to go through this new project and our expectations and standards we were aiming to follow

Try and enforce the standards via Visual Studio (not sure if this would be possible or how just an idea)

At the moment there is no general company programming standards so this would be a first really insofar as we are creating a standard that different project teams would need to adhere to.


答:
I did this once a few years ago, back in the days of Managed C++.  We had some business logic in an umanaged DLL that we wanted to incorporate into a wizard-style GUI written in C#.  To do this, I created a Managed C++ assembly to sit between the managed GUI app and the unmanaged DLL and used System::Runtime::InteropServices::Marshal within that assembly to convert values from managed types (System::Int32) to unmanaged types (int) and vice versa.

While Managed C++ appears to be deprecated, the same principal might apply to C++/CLI.


问:
Versioning Within a Platform
I work with a few different web platforms, and my actual projects are typically quite small, and live within those platforms.  The project files are scattered throughout the platform tree, which makes versioning a little awkward.  I've been keeping one repository per platform, which gets out of hand quite fast...

The biggest problem I've had is with Eclipse + SVN, and the size of the project keeps growing, despite working with a fairly static platform/library, and only a handful of files for the given project at a time.  In order for the project to work, I need them within the platform tree.

I'm wanting to move entirely to Git soon, so I'm just figuring out how I can keep the projects separate, yet keep the development environment working efficiently.

I've been looking into some sort of file sync (rsync, but real time?), since the solution makes sense in my head.  I'll keep projects out of the tree, and use a file sync to ensure they are copied in real time.  This keeps the projects we work on very small and quick, and keeps the actual platform working properly.  However, I've been having troubles finding the correct software to make this work properly.  Any suggestions in this area would also be appreciated...

Am I looking at this the wrong way?  What are some other possible solutions?  It seems like a common problem, yet I can't find much information on how to solve it.

Thanks!

答:
If the app(s} share a common purpose, featureset, and theme; but vary slightly in how they are implemented at the core OS, DB, or other service provider level, it's often common to see source tree layouts organized something similar to this, where dependancies are properly isolated at the lowest sublevels.  Certainly you may end up with a deeper or wider heirarchy depending on logical organization and physical components, but this is the gist of it:

[App Package]

[Platform Agnostic Subpackage]

[MSW x86 32 Platform Subpackage]

[MSW x64 Platform Subpackage]

[HPUX RISC 64 Platform Subpackage]

[Common Subpackage]

[Data Provider Agnostic Subpackage]

[Oracle Db Client Platform Agnostic Subpackage]

[Oracle Db Client for MSW x86 32 Subpackage]

[Oracle Db Client for MSW x64 Subpackage]

[Oracle Db Client for HPUX RISC 64]

[MySql Db Package]

With each project 'working copy' and 'build' pulling the parts it needs from source control, and leaving what it doesn't need behind.

Title: Versioning Within a Platform


问:
Is it OK for me to suggest ready-made scripts to a programmer? If so, how can I do it without offending him/her?
Is it ok to suggest pre-built scripts from a place like codecanyon to a programmer who is building a startup web app? Or is it more likely to offend?

I don't expect that a whole web app could be built from bits and bobs purchased from a site but I'm unsure of whether its the right thing to ask someone to do.

Also, I am not a programmer.

答: Developers might prefer you tell them that the scripts are available for use, rather than use these scripts. Developers are lazy though and they will copy/paste anything and everything they can get away with rather than re-type something, they also like having at least the illusion of free will.</p>


答:
Ultimately, as the customer you can demand that they make you a website out of baling wire and scotch tape.

This may decrease the number of people who apply.

I would suggest, if you have someone in mind already, that you discuss the purchase with them. If they want the script(s), go ahead with the purchase. A professional developer may look at the scripts and tell you that their functionality is replicated in some open source package.

You are free to do whatever you want, it is your business decision to make. However, you are presumably hiring the developer because they possess knowledge and skills that you do not, and it would behoove you to take advantage of the service you are paying for.

Title: Is it OK for me to suggest ready-made scripts to a programmer? If so, how can I do it without offending him/her?

Body:
Is it ok to suggest pre-built scripts from a place like codecanyon to a programmer who is building a startup web app? Or is it more likely to offend?

I don't expect that a whole web app could be built from bits and bobs purchased from a site but I'm unsure of whether its the right thing to ask someone to do.

Also, I am not a programmer.


答:
While it would seem like option 2 would be the sensible answer, it all depends on the context. Objects are not mainly for keeping data, but for modeling behavior. This means that to answer the question properly we need to know a lot more about what behavior the system should support. For instance it might be that the Profile is actually the most important concept in this system, and that the user should be hanging off of it. Or maybe there shouldn't even be a Profile class (or a User class), but some other classes based on what actions the user is to perform.

So the answer is: There is not answer!

Title: Best way to handle class relationship

Body:
Take a User class and the idea that a User is to be profiled. I see four ways to handle this:

Write the code for the profile into the User class. I am dismissing this right away.

Create a Profile class and make it a property of the User class.

Write a User class (with the boiler-plate name, address stuff), write a Profile class,
and write a UserProfile class - UserProfile is the union of User and Profile.

Write a User class and a Profile class that each have an ID property and let the ID act
as the intersection. This way the User and Profile are independent and another class,
possibly an abstract class with nothing but static methods handles the logic that
describes the connection.

Choices 3 and 4 each require at least three classes. For this case, which is the best choice? If possible to generalize this, would it generally be better to use one of these possibilities?


问:
How can I design an application so that it works well with a database selected by the customer?
I want to write an ASP.NET 4.0 application with IBM DB2 Express-C as its back-end. One thing that worries me, is hosting this application on a remote server. I don't know any hosting provider who provides ASP.NET DB2 hosting in the same price range as of SQL Server.

I also want to allow the customer to select the database of their choice from this list:

SQL Sever

Oracle

DB2

PostgreSQL

Firebird

There are the same hosting worries with Oracle and Firebird.

Hosting issues aside, I want to know how to design an application so it is agnostic to the kind of RDBMS used and will work with any of the above mentioned ones.

Are there any such applications around?

答:
You can and should abstract out your data layer. However, before you arbitrarily decide that your aim is to support multiple databases you need to realise that:

All databases have their quirks and behave in different ways, so even if you use an ORM (the entity framework is OK, but I'm not convinced about how good it is for large data volumes) you need to be aware that it might not work identically for all databases (distributed transactions may or may not be supported for example). Given this you increase your development cost, possibly considerably, if you want to provide a consistent experience across all databases.

Even if you ORM is Awesome and does everything identically in every database, you still need to run all of your acceptance tests in each database environment to confirm this which definitely increases your QA costs.

Now you are writing a .NET website, by the sound of it for the consumer market, so it will be hosted on a box somewhere like Godaddy with access to a SQL Server database as part of the package.

Given that what is the expected return on investment from supporting any database other than SQL Server?

I would say that only if you think this figure is positive and in proportion with your other development costs should you consider supporting more than one database, and then only support other databases once your product is established and stable with a SQL Server back end and there is a definite demand from your customers.


问:
Should I avoid private methods if I perform TDD?
I'm just now learning TDD. It's my understanding that private methods are untestable and shouldn't be worried about because the public API will provide enough information for verifying an object's integrity.

I've understood OOP for a while. It's my understanding that private methods make objects more encapsulated, thus more resistant to change and errors. Thus, they should be used by default and only those methods that matter to clients should be made public.

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Also, it's considered bad practice to add methods for the sake of testing.

Does this mean TDD is at odds with encapsulation? What is the appropriate balance? I'm inclined to make most or all of my methods public now...

答:
You should not need to abandon using private methods. It's perfectly reasonable to use them, but from a testing perspective they are harder to test directly without either breaking encapsulation or adding test-specific code to your classes. The trick is to minimize the stuff that you know is going to make your gut squirm because you feel like you've dirtied your code.

These are the things that I keep in mind to try and achieve a workable balance.

Minimize the number of private methods and properties that you use. Most of the stuff you need your class to do tends to need to be exposed publicly anyway, so have a think about whether you really do need to make that clever method private.

Minimize the amount of code in your private methods - you really should be doing this anyway - and test indirectly where you can via the behavior of other methods. You never expect to get 100% test coverage, and perhaps you will need to hand check a few values via the debugger. Using private methods to throw Exceptions can easily be tested indirectly. Private properties may need to be tested manually, or via another method.

If indirect or manual checking doesn't sit well with you, add a protected event and access via an Interface to expose some of the private stuff. This effectively "bends" the rules of encapsulation, but avoids the need to actually ship code that executes your tests. The drawback is that this can result in a little additional internal code to make sure that the event will be fired when needed.

If you feel that a public method isn't "secure" enough, see if there are ways you can implement some sort of validation process in your methods to limit how they are used.  Chances are that while you are thinking this through either think of a better way to implement your methods, or you'll see another class beginning to take shape.

If you have a lot of private methods doing "stuff" for your public methods, there may be a new class waiting to be extracted.  You can test this directly as a separate class, but implement as a composite privately within the class that uses it.

Think laterally. Keep your classes small and your methods smaller, and use lots of composition.  It sounds like more work, but in the end you'll end up with more individually testable items, your tests will be simpler, you'll have more options for using simple mocks in place of real, large and complex objects, hopefully well-factored and loosely coupled code, and more importantly you'll give your self more options. Keeping things small tends to save you time in the end, because you reduce the number of things you need to individually check on each class, and you tend to naturally reduce the code spaghetti that can sometimes happen when a class gets large and has lots of interdependent code behavior internally.