问:
Refactoring - Utility classes behavior under a common interface
I was suggested to put my question here, so I'm doing so ;)

I need a common interface which represents some specific behavior:

```<code>public interface Contract(){
   public void methodA();
   public void methodB();
   // and so on...
}
</code>```

The problem is, that in order to fulfill this behavior, implementation can be totally stateless - it can have a private constructor and expose only static methods:

```<code>public class MyUtilityClass /*implements Contract*/{
   private MyUtilityClass(){}
   public static void methodA(){
      // some implementation here...
   }
   public static void methodB(){
      // some implementation here...
   }
}
</code>```

I have many such classes, with different behavior, so I want to refactor them and handle under a common interface.

Because I cannot implement Contract by means of static methods, is the only solution to convert MyUtilityClass to a singleton which implements the interface in order to achieve my goal? Or maybe would you suggest something else? For example Template method and Strategy which can by injected depending on a specific situation?

What would you propose?

答:
Inside your utility class:

```<code>private static final Contract CONTRACT = new Contract() { // implement methods };
</code>```

Now, you can wrap its methods or return that instance and use its methods directly, it's up to you.

EDIT:
Another idea crossed my mind: Singletons can be created using enums too. And enums can implement interfaces!

Body:
Inside your utility class:

private static final Contract CONTRACT = new Contract() { // implement methods };

Now, you can wrap its methods or return that instance and use its methods directly, it's up to you.

EDIT:
Another idea crossed my mind: Singletons can be created using enums too. And enums can implement interfaces!


问:
I am a beginner. Can I directly start learning C++11? or I have to learn old C++?
I'm a beginner and have only little knowledge in programming.

Would it be good if I directly learn C++ from books which cover new C++11 or should I study through the old best C++ books?

Should I have little knowledge about C++ before learning C++11? or I can start directly from there?

Would it cause problem if I directly start from C++11? If no, then suggest some books on C++11.

答:
Despite many improvements in C++11, C++ is still not an easy language. Java, while not as easy as some may think, is still an easier language with very good performance (often almost as fast as C++) and offers better IDEs (maybe Visual C++ is as good as current Java IDEs but no luck here on Linux), a much more comprehensive standard library (the JDK), more libraries (e.g. Hibernate, Spring, JEE, Lucene, etc) and no memory leaks (well, almost none – you can still build a memory leak in Java but it is more difficult to do so than in C++). To be fair, with modern C++11, it is much easier to avoid memory leaks.

C++11 has many cool features like lambdas, auto keyword, move semantics, and much more. It is definitely a much better language than C++98 was.
See this overview by Herb Sutter about the new features in C++11:
Elements of Modern C++ Style.

To sum up, I think everyone should learn at least some C++. If you have been programming in Java, Scala, Ruby or Python for the last decade and never touched C or C++, now with C++11 I think it is time to learn C++11 and improve your programming skills while doing so.

I probably won’t be using C++ much at work in the coming years and when I need a more powerful language than Java, I will probably go for Scala, but I will have a closer look at C++11 and try to learn and understand the new features, particularly those about multithreading and concurrency.

Remember: It always helps to learn a new programming language even
when you don’t plan to use it in production.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Are classes with only a single (public) method a problem?
I am currently working on a software project that performs compression and indexing on video surveillance footage. The compression works by splitting background and foreground objects, then saving the background as a static image, and the foreground as a sprite.

Recently, I have embarked on reviewing some of the classes that I have designed for the project.

I noticed that there are many classes that only have a single public method. Some of these classes are:

VideoCompressor (with a compress method that takes in an input video of type RawVideo and returns an output video of type CompressedVideo).

VideoSplitter (with a split method that takes in an input video of type RawVideo and returns a vector of 2 output videos, each of type RawVideo).

VideoIndexer (with an index method that takes in an input video of type RawVideo and returns a video index of type VideoIndex).

I find myself instantiating each class just to make calls like VideoCompressor.compress(...), VideoSplitter.split(...), VideoIndexer.index(...).

On the surface, I do think the class names are sufficiently descriptive of their intended function, and they are actually nouns. Correspondingly, their methods are also verbs.

Is this actually a problem?

答:
It is a problem - you are working from the functional aspect of the design, rather than the data. What you actually have are 3 standalone functions that have been OO-ified.

For example, you have a VideoCompressor class. Why are you working with a class designed to compress video - why do you not have a Video class with methods on it to compress the (video) data that each object of this type contains?

When designing OO systems, its best to create classes that represent objects, rather than classes that represent activities that you can apply. In the old days, classes were called types - OO was a way to extend a language with support for new data types. If you think of OO like this, you get a better way of designing your classes.

EDIT:

let me try to explain myself a little better, imagine a string class that has a concat method. You can implement such a thing where each object instantiated from the class contains the string data, so you can say

```<code>string mystring("Hello");
mystring.concat("World");
</code>```

but the OP wants it to work like this:

```<code>string mystring();
string result = mystring.concat("Hello", "World");
</code>```

now there are places where a class can be used to hold a collection of related functions, but that is not OO, its a handy way of using the OO features of a language to help manage your codebase better, but it is no way any kind of "OO Design". The object in such cases is totally artificial, simply used like this because the language does not offer anything better to manage this kind of problem. eg. In languages such as C# you would use a static class to provide this functionality - it reuses the class mechanism, but you no longer need to instantiate a object just to call the methods on it. You do end up with methods like string.IsNullOrEmpty(mystring) which I think is poor compared to mystring.isNullOrEmpty().

So, if anyone is asking "how do I design my classes", I recommend thinking of the data the class will contain rather than the functions it contains. If you go for the "a class is a bunch of methods", then you end up writing "better C" style code. (which isn't necessarily a bad thing if you are improving C code) but it is not going to give you the best OO designed program.

Body:
It is a problem - you are working from the functional aspect of the design, rather than the data. What you actually have are 3 standalone functions that have been OO-ified.

For example, you have a VideoCompressor class. Why are you working with a class designed to compress video - why do you not have a Video class with methods on it to compress the (video) data that each object of this type contains?

When designing OO systems, its best to create classes that represent objects, rather than classes that represent activities that you can apply. In the old days, classes were called types - OO was a way to extend a language with support for new data types. If you think of OO like this, you get a better way of designing your classes.

EDIT:

let me try to explain myself a little better, imagine a string class that has a concat method. You can implement such a thing where each object instantiated from the class contains the string data, so you can say

string mystring("Hello");
mystring.concat("World");

but the OP wants it to work like this:

string mystring();
string result = mystring.concat("Hello", "World");

now there are places where a class can be used to hold a collection of related functions, but that is not OO, its a handy way of using the OO features of a language to help manage your codebase better, but it is no way any kind of "OO Design". The object in such cases is totally artificial, simply used like this because the language does not offer anything better to manage this kind of problem. eg. In languages such as C# you would use a static class to provide this functionality - it reuses the class mechanism, but you no longer need to instantiate a object just to call the methods on it. You do end up with methods like string.IsNullOrEmpty(mystring) which I think is poor compared to mystring.isNullOrEmpty().

So, if anyone is asking "how do I design my classes", I recommend thinking of the data the class will contain rather than the functions it contains. If you go for the "a class is a bunch of methods", then you end up writing "better C" style code. (which isn't necessarily a bad thing if you are improving C code) but it is not going to give you the best OO designed program.


问:
Database model for keeping track of likes/shares/comments on blog posts over time
My goal is to keep track of the popular posts on different blog sites based on social network activity at any given time. The goal is not to simply get the most popular now, but instead find posts that are popular compared to other posts on the same blog.

For example, I follow a tech blog, a sports blog, and a gossip blog. The tech blog gets waaay more readership than the other two blogs, so in raw numbers every post on the tech blog will always out number views on the other two. So let's say the average tech blog post gets 500 fb likes and the other two get an average of 50 likes per post. Then when there is a sports blog post that has 200 Facebook likes and a gossip blog post with 300 while the tech blog posts today have 500 likes I want to highlight the sports and gossip blog posts (more likes than average vs tech blog with more # of likes but just average for the blog)

The approach I am thinking of taking is to make an entry in a database for each blog post. Every x minutes (say every 15 minutes) I will check how many likes/shares/comments an entry has received on all the social networks (Facebook, Twitter, Google+, LinkedIn). So over time there will be a history of likes for each  blog post, i.e

```<code>   post 1234

        after 15 min: 10 fb likes, 4 tweets, 6 g+
        after 30 min: 15 fb likes, 15 tweets, 10 g+
        ...
        ...
        after 48 hours: 200 fb likes, 25 tweets, 15 g+
</code>```

By keeping a history like this for each blog post I can know the average number of likes/shares/tweets at any give time interval. So for example the average number of fb likes for all blog posts 48hrs after posting is 50, and a particular post has 200 I can mark that as a popular post and feature/highlight it. A consideration in the design is to be able to easily query the values (likes/shares) for a specific time-frame, i.e. fb likes after 30min or tweets after 24 hrs in-order to compute averages with which to compare against (or should averages be stored in it's own table?)

If this approach is flawed or could use improvement please let me know, but it is not my main question. My main question is what should a database scheme for storing this info look like?

Assuming the approach above is taken, I am trying to figure out what a database schema for storing the likes over time would look like. I am brand new to databases, in doing some basic reading I see that it is advisable to make a 3NF database. I have come up with the following possible schema.

Schema 1

```<code>DB Popular Posts

  Table: Post
    post_id ( primary key(pk) )
    url
    title

  Table: Social Activity
    activity_id (pk)
    url (fk)
    type (i.e. facebook,twitter,g+)
    value
    timestamp
</code>```

This was my initial instinct (base on my very limited db knowledge). As far as I under stand this schema would be 3NF? I searched for designs of similar database model, and found this question on weight/height storage of multiple users. The scenario in that question is similar (recording weight/height of users overtime). Taking the accepted answer for that question and applying it to my model results in something like:

Schema 2 (same as above, but break down the social activity into 2 tables)

```<code>DB Popular Posts

  Table: Post
    post_id (pk)
    url
    title

  Table: Social Measurement
    measurement_id (pk)
    post_id (fk)
    timestamp

  Table: Social stat
    stat_id (pk)
    measurement_id (fk)
    type (i.e. facebook,twitter,g+)
    value
</code>```

The advantage I see in schema 2 is that I will likely want to access all the values for a given time, i.e. when making a measurement at 30min after a post is published I will simultaneous check the number of fb likes, fb shares, fb comments, tweets, G+, LinkedIn. So with this schema it may be easier get get all stats for a measurement_id corresponding to a certain time, i.e. all social stats for post 1234 at time x.

Another thought I had is since it doesn't make sense to compare number of fb likes with number of tweets or g+ shares, maybe it makes sense to separate each social measurement into its own table?

Schema 3

```<code>DB Popular Posts

  Table: Post
    post_id (pk)
    url
    title

  Table: fb_likes
    fb_like_id (pk)
    post_id (fk)
    timestamp
    value

  Table: fb_shares
    fb_shares_id (pk)
    post_id (fk)
    timestamp
    value

  Table: tweets
    tweets__id (pk)
    post_id (fk)
    timestamp
    value

  Table: google_plus
    google_plus_id (pk)
    post_id (fk)
    timestamp
    value
</code>```

As you can see I am generally lost/unsure of what approach to take.

I'm sure this typical type of database problem (storing measurements overtime, i.e temperature statistic) that must have a common solution. Is there a design pattern/model for this, does it have a name? I tried searching for "database periodic data collection" or "database measurements over time" but didn't find anything specific.

What would be an appropriate model to solve the needs of this problem?

答:
To answer the questions you want to ask your application you need to store information about three things: blogs, posts and activities.

Blogs are simply containers for the posts, because you said you want to rank/highlight posts within each of the blogs, not across the blogs, so you need to know which posts belong to which blogs. Posts are fairly static, but are independent of their respective blogs and their social activity. Social activity is highly dynamic (probably looks like a bell curve over time) and there may or may not be a cut-off for the social activity discovery over time.

Now, this leaves you with three core entities: blog, post and activity. The schema could look something like this:

```<code>blog          post          activity
----------    -----------   --------
blog_id (pk)  post_id (pk)  activity_id (pk)
url           blog_id (fk)  post_id (fk)
title         url           facebook_likes
              title         twitter_tweets
                            google_shares
</code>```

This assumes that you're not interested in storing the actual social media activity itself, i.e. storing the URL of the tweet, etc, and just storing the results of the social activity discovery for each post. If you run this for a new post today, you would insert the results into the activity table. If you run the discovery again tomorrow, a row in the activity table would already exist and you'd update it with the results at that time.

(Feature creep alert: if you store new rows for each discovery you could gain some valuable insight into how the social media activity develops over time. For instance, you could see which medium is quick to pick up the post and which lag behind. And you could create some useful graphs that would spice up the presentation. In order to do this you'd need to store exactly the same things, but also add a date/timestamp for when the discovery was done.)

A foreign key connects the row to a row in another table. So for instance, a blog has multiple posts, and a post belongs to a single blog. This is a one to many relation -- one blog has many posts, a post belongs to one and only one blog. A blog could have the blog_id 1. All posts that belong to that blog would have their blog_id set to 1.

Technically speaking you could eliminate the activity table and move the columns into the post table if you wanted to. The reason I'm keeping them separate is that they're distinct entities and it leaves the door open for future changes. For instance you could easily add a timestamp and store the activity as something that varies over time. Furthermore, you could break it down even more and add another table (e.g. action) that stores the actual individual social media actions (the tweets, the likes, etc).

As an optimization you can compute and store the metrics on the respective entities (i.e. table and post) if need be. This is primarily a concern when it comes to reading the data after you've done the discovery. Remember you'll be computing and updating the database very little compared to how many times your users will be reading the information -- in other words, denormalizing and aggregating will reduce the number of queries needed to produce the data you want to present to your users.

Body:
To answer the questions you want to ask your application you need to store information about three things: blogs, posts and activities.

Blogs are simply containers for the posts, because you said you want to rank/highlight posts within each of the blogs, not across the blogs, so you need to know which posts belong to which blogs. Posts are fairly static, but are independent of their respective blogs and their social activity. Social activity is highly dynamic (probably looks like a bell curve over time) and there may or may not be a cut-off for the social activity discovery over time.

Now, this leaves you with three core entities: blog, post and activity. The schema could look something like this:

blog          post          activity
----------    -----------   --------
blog_id (pk)  post_id (pk)  activity_id (pk)
url           blog_id (fk)  post_id (fk)
title         url           facebook_likes
              title         twitter_tweets
                            google_shares

This assumes that you're not interested in storing the actual social media activity itself, i.e. storing the URL of the tweet, etc, and just storing the results of the social activity discovery for each post. If you run this for a new post today, you would insert the results into the activity table. If you run the discovery again tomorrow, a row in the activity table would already exist and you'd update it with the results at that time.

(Feature creep alert: if you store new rows for each discovery you could gain some valuable insight into how the social media activity develops over time. For instance, you could see which medium is quick to pick up the post and which lag behind. And you could create some useful graphs that would spice up the presentation. In order to do this you'd need to store exactly the same things, but also add a date/timestamp for when the discovery was done.)

A foreign key connects the row to a row in another table. So for instance, a blog has multiple posts, and a post belongs to a single blog. This is a one to many relation -- one blog has many posts, a post belongs to one and only one blog. A blog could have the blog_id 1. All posts that belong to that blog would have their blog_id set to 1.

Technically speaking you could eliminate the activity table and move the columns into the post table if you wanted to. The reason I'm keeping them separate is that they're distinct entities and it leaves the door open for future changes. For instance you could easily add a timestamp and store the activity as something that varies over time. Furthermore, you could break it down even more and add another table (e.g. action) that stores the actual individual social media actions (the tweets, the likes, etc).

As an optimization you can compute and store the metrics on the respective entities (i.e. table and post) if need be. This is primarily a concern when it comes to reading the data after you've done the discovery. Remember you'll be computing and updating the database very little compared to how many times your users will be reading the information -- in other words, denormalizing and aggregating will reduce the number of queries needed to produce the data you want to present to your users.


答:
The singleton is a creational pattern, and it's only about how many instances of a particular class exist, not about how they're used. By creating singletons you solve the problem of getting rid of the static methods, and thus you can introduce your common interface. That's the solution of your problem.

The moment all your classes implement a common interface you should refer to them using the abstraction. Then, you might if you want use a strategy pattern and exchange at runtime the particular implementation to be used. Strategy is a behavioral pattern, and in my opinion has nothing to do with your problem.

Title: Refactoring - Utility classes behavior under a common interface

Body:
I was suggested to put my question here, so I'm doing so ;)

I need a common interface which represents some specific behavior:

```<code>public interface Contract(){
   public void methodA();
   public void methodB();
   // and so on...
}
</code>```

The problem is, that in order to fulfill this behavior, implementation can be totally stateless - it can have a private constructor and expose only static methods:

```<code>public class MyUtilityClass /*implements Contract*/{
   private MyUtilityClass(){}
   public static void methodA(){
      // some implementation here...
   }
   public static void methodB(){
      // some implementation here...
   }
}
</code>```

I have many such classes, with different behavior, so I want to refactor them and handle under a common interface.

Because I cannot implement Contract by means of static methods, is the only solution to convert MyUtilityClass to a singleton which implements the interface in order to achieve my goal? Or maybe would you suggest something else? For example Template method and Strategy which can by injected depending on a specific situation?

What would you propose?


问:
What is ServletUtilities?
The answer in this question suggests creating a ServletUtilities class to handle text conversion between Java strings and XML text.

Generally when you create a JEE web application you put together a
  class that handles general conversions like this in a class named
  ServletUtilities.

I did a bit of a google for ServletUtilities, but I can't find much about it.

Is having a ServletUtilities class a convention?

How common is it?

When should you have one?

When should it be used?

答:
Collecting static methods in classes called SomethingUtilities (or SomethingUtils or SomethingUtil) is a pretty widespread convention, but ServletUtilities as such is not.

Excessive use of such classes can be a sign that the author of the code has not really understood object orientation and is writing procedural code in an OO language, whereas moderate use of them just shows that for some tasks you really want standalone functions rather than classes.

Note that the code in the answer you cite is bad for a number of reasons:

The name of the class should be directly related to what the static methods do, and XML escaping has nothing to do with Servlets.

XML escaping is a very common task and potentially security-relevant, so you really shouldn't roll your own. Any XML parser or framework will have a way to do it that is almost certainly better than what you'll come up with on the fly. Or you can use Apache commons-lang which has StringEscapeUtils.escapeXml() (better class name, too!)

Title: What is ServletUtilities?


答:
it can have a private constructor and expose only static methods

Yes, it can, but there is no technical need for. So (besides some other good suggestions here) you should also consider the most simple solution for your problem, just to abandon the "static" keyword.


问:
When should a database table use timestamps?
First a note, I thought maybe this question belonged in the database exchange, but I think it is more broadly related to a programming solution as a whole than to databases. Will move to database exchange if people think thats the best one.

I was wondering when a database table should have a created and updated timestamp added?

The first obvious answer is that if any business logic needs to know when something was updated (like a transaction completion date etc) then it must go in.

But what about non business logic cases? For example I can think of scenarios where it would be really useful to know the date time that rows changed to help with fault finding e.g. some business logic is failing and looking at the related database rows its possible to identify that one row is being update before another row which is causing the error.

With this use case, it would make sense to give every table an update and create timestamp (except for maybe the most trivial enum tables that wouldn't be updated by any part of the application).

Giving every table a timestamp is surely a great way to quickly bog down a database (although could be wrong).

So when should a database table use create and update timestamps?

答:
The way the question is worded, you're asking for a list of things. I'm going to risk not directly answering your question, but answering when you should use an alternate solution.

I can think of scenarios where it would be really useful to know the
  date time that rows changed to help with fault finding

Would it be more useful to have a log of all the updates for a given record? Just knowing the last update, may not be enough information. This log could be put in a separate table. It would be more convenient to track changes from several tables in the same log file(s) (it doesn't have to be a table). This prevents some massive union query of all table change_dates to get aggregates. This would also benefit trouble-shooting by helping you see a recording of more events in your system.

In Addition: You have to consider the users as well. They may not make it a business case, but when you have inexperienced users or those in a corporate culture where they never make a user error and want to always blame it on the computer, any kind of logging will help including update dates on tables. In this case, you may want to have an Update_UserID field as well.


问:
How to ensure that all the customers have the latest version of web application deployed on intranet?
How to update web application deployed on intranet? There is a Java Spring application that will be deployed on intranet of multiple customers.

In case when there is a major update what should the developer do in order to ensure that all the customers have the latest version of his software?

There is an option that an update module is implemented in the application and it will automatically query the central web repository for updates. This option doesn't work if there is the server where the application is installed doesn't have internet connection.

Another possibility that comes to mind is to manually send a .war file to the IT personnel of all the customers for them to install the latest version.

How to deal with updates in this situation?

答:
I can think of several options:

a) keep track of which software version each customer is running and when you have a new release, inform the customer of this along with instructions on how to obtain and apply the update. This is a manual process that can be largely automated.

b) if the site has Internet connectivity you can write an in-app module that periodically checks for updates and downloads the update to the server. An authorized person could then be informed via email and manually apply the update out-of-app (e.g. logging in to the server and running a script) or by in-app approval (e.g. the app sets a flag that a privileged script on the app server picks up and applies the update). This is a manual/semi-automatic process that the customer controls.

c) install your update program on the server and have it periodically phone home and check for updates. If an update is found, download it and at the right time, automatically update the server. In the case of a war file, you could run a script from cron that checks, downloads, halts the app server, replaces the war file, and starts the app server again. If the site's connectivity is poor or the update is big, consider keeping the retrieval and update separate so as to leave enough time for both. This is an automated solution so beware -- make sure the customer is okay with it and understands the implications.

d) if no Internet connectivity you really can't automate much of the discovery and retrieval. You can, however, make it easy for the person responsible to apply the update. For instance, by offering clear instructions on how to get the update onto portable media such as a memory stick, CD-ROM, or whatever. It greatly helps to know their environment so that you can tailor the instructions -- it depends on how skilled they are.

If your update is packaged as a complete application war file (as you mentioned) then it's a pretty simple process as you're simply updating the entire application, and not individual components. But both can be done, though patching can be more involved. If you have a standardized stack at each customer site then you can write something that's automated and robust. The devil's in the details so the more information you can provide on the application stack the better, particularly what operating system and application server you're running on, and what the connectivity with the world is (Internet and also users clients, e.g. is it easy to get a file onto the server from a client -- for instance, if clients have Internet access (e.g. email, web) they could save the update to an SMB share on the app server and a script would pick it up from there).

I hope this gives you some ideas.


问:
How do you format arrays within parameters?
I'm talking about something like this:

```<code>echo $form->input('general_addresss', array(
            'label' => 'Where will you go today?'
            'format' => array('before', 'input', 'after', 'label', 'after', 'error')
            ));
</code>```

Do you start with one array parameter, then break a line? If it can't fit on a line, do you immediately break a line?

After of which, do you do a set number of tabs over? What happens if an array within an array has lots of properties?

Is there any particular guide you follow?

答:
I do it like this:

```<code>echo $form->input
    (
        'general_addresss',
        array
        (
            'label' => 'Where will you go today?'
            'format' => array
            (
                'before',
                'input',
                'after',
                'label',
                'after',
                'error'
            )
        )
    );
</code>```

It may seem like a massive overkill of whitespace, but I find it quite readable and obvious - none of my brackets are hidden and everything is nicely indented visually. YMMV ;)

Edit: Regarding the "particular guide", my particular guide are my eyes. If I can't quickly see where I left my keys in the source code, it's probably badly formatted.

p.s. You must be coming from CakePHP :)

ContentLicense: CC BY-SA 2.5

Body:
I do it like this:

echo $form->input
    (
        'general_addresss',
        array
        (
            'label' => 'Where will you go today?'
            'format' => array
            (
                'before',
                'input',
                'after',
                'label',
                'after',
                'error'
            )
        )
    );

It may seem like a massive overkill of whitespace, but I find it quite readable and obvious - none of my brackets are hidden and everything is nicely indented visually. YMMV ;)

Edit: Regarding the "particular guide", my particular guide are my eyes. If I can't quickly see where I left my keys in the source code, it's probably badly formatted.

p.s. You must be coming from CakePHP :)


答:
It is no longer object oriented. Because those classes don't represent anything, they are just vessels for the functions.

That does not mean it's wrong. If the functionality is sufficiently complex or when it's generic (i.e. the arguments are interfaces, not concrete final types), it makes sense to put that functionality in separate module.

From there it depends on your language. If the language has free functions, they should be modules exporting functions. Why pretend it's a class when it isn't. If the language does not have free functions like e.g. Java, then you create classes with single public method. Well, that just shows the limits of object oriented design. Sometimes functional is simply better match.

There is one case when you may need a class with single public method because it has to implement interface with single public method. Be it for observer pattern or dependency injection or whatever. Here it again depends on the language. In languages that have first class functors (C++ (std::function or template parameter), C# (delegate), Python, Perl, Ruby (proc), Lisp, Haskell, ...) these patterns use function types and don't need classes. Java does not (yet, will in version 8) have function types, so you use single method interfaces and corresponding single method classes.

Of course I am not advocating writing single huge function. It should have private subroutines, but they can be private to the implementation file (file-level static or anonymous namespace in C++) or in a private helper class that is only instantiated inside the public function (To store data or not?).

Title: Are classes with only a single (public) method a problem?

Body:
I am currently working on a software project that performs compression and indexing on video surveillance footage. The compression works by splitting background and foreground objects, then saving the background as a static image, and the foreground as a sprite.

Recently, I have embarked on reviewing some of the classes that I have designed for the project.

I noticed that there are many classes that only have a single public method. Some of these classes are:

VideoCompressor (with a compress method that takes in an input video of type RawVideo and returns an output video of type CompressedVideo).

VideoSplitter (with a split method that takes in an input video of type RawVideo and returns a vector of 2 output videos, each of type RawVideo).

VideoIndexer (with an index method that takes in an input video of type RawVideo and returns a video index of type VideoIndex).

I find myself instantiating each class just to make calls like VideoCompressor.compress(...), VideoSplitter.split(...), VideoIndexer.index(...).

On the surface, I do think the class names are sufficiently descriptive of their intended function, and they are actually nouns. Correspondingly, their methods are also verbs.

Is this actually a problem?


答:
```<code>what should the developer do in order to ensure that all the customers have the latest version of his software?
</code>```

Absolutely nothing except for informing the ones responsible for deployment of the application, that there's a new version.

It's not the repsonsibility of a developer to deploy applications.

So, inform that IT of said customer and send them the .war file. This way they have the ability to test the application on whatever they want to test it before deploying it. It is often seen as bad form for applications just to update themselves, ignoring IT.

Title: How to ensure that all the customers have the latest version of web application deployed on intranet?

Body:
How to update web application deployed on intranet? There is a Java Spring application that will be deployed on intranet of multiple customers.

In case when there is a major update what should the developer do in order to ensure that all the customers have the latest version of his software?

There is an option that an update module is implemented in the application and it will automatically query the central web repository for updates. This option doesn't work if there is the server where the application is installed doesn't have internet connection.

Another possibility that comes to mind is to manually send a .war file to the IT personnel of all the customers for them to install the latest version.

How to deal with updates in this situation?

Body:
what should the developer do in order to ensure that all the customers have the latest version of his software?

Absolutely nothing except for informing the ones responsible for deployment of the application, that there's a new version.

It's not the repsonsibility of a developer to deploy applications.

So, inform that IT of said customer and send them the .war file. This way they have the ability to test the application on whatever they want to test it before deploying it. It is often seen as bad form for applications just to update themselves, ignoring IT.


问:
Fail-fast paradigm overheads
Fail-fast seems like a right way since it simplifies bug detection. But it's a harm for performance cause of multiple checking the same thing at several levels of the system.

Simple example.
There is a function that input parameters must be not null. And there is function wrapping it, that also await the same parameters also not null. After some activities function-wrapper passes input parameters into first one. So that the same items checked two times: at the beginning of function wrapper and inside wrapped function.

So I would like to know how much widespread this style is. Should I write fail-fast code or check everything just once?

答:
Early checking of preconditions will be as fast or faster than doing the same checks in the middle of your calculation.
The italic part is where your reasoning goes astray. Fail-fast/early checking does not mean you check more things or check them more often, it means that you perform the same checks earlier in the calculation (preferably before you start doing any 'real work' in a function).

To take your example of two functions (Foo and Bar) where both require their parameters to be non-null and Foo invokes Bar passing some of its parameters on.

With early checking, both function check if their parameters meet the precondition of being non-null.

Without early checking, both functions still need to make sure that their parameters are non-null, but the check gets delayed until the first use of the parameter and, worst case, has to be repeated on each subsequent use (depending on the code structure).

If, without early checking, Bar doesn't verify that the parameters are non-null (trusting that the check has already been done in Foo), then the same trust can be used to leave out the check in the early checking case.

Title: Fail-fast paradigm overheads


答: In C/C++ it is even common not to apply any check at all (if you have no debug code). Having a function like memcpy and making it checking the arguments implies a serious overall overhead. Hence preconditions are applied to the usage of the function (putting all responsibility to the programmer). The best 'fail fast' is a failure at compilation time. With C++ it could be a function taking a reference and no pointer (but it will not prevent a programmer to dereference a pointer and pass that).</p>

Title: Fail-fast paradigm overheads

Body:
Fail-fast seems like a right way since it simplifies bug detection. But it's a harm for performance cause of multiple checking the same thing at several levels of the system.

Simple example.
There is a function that input parameters must be not null. And there is function wrapping it, that also await the same parameters also not null. After some activities function-wrapper passes input parameters into first one. So that the same items checked two times: at the beginning of function wrapper and inside wrapped function.

So I would like to know how much widespread this style is. Should I write fail-fast code or check everything just once?


问:
Pattern for costly precondition check before acting
Let's say I have a method DoTheThing() which requires the precondition-check CanTheThingBeDone() to return true. The latter method is time consuming as it accesses the database.

I'm finding it hard to find a perfect way to perform the precondition check effectively (i.e. once) while maintaining both readability and API integrity. Observe these examples:

Example 1:

```<code>class System() {
    public void DoTheThing() {
        if (!CanTheThingBeDone()) throw new Exception(...);
        // Do it
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        try {
            system.DoTheThing();
        }
        catch (Exception) {
            // Error handling
        }
    }
}
</code>```

Example 2:

```<code>class System() {
    public void DoTheThing() {
        // Do it
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        if (system.CanTheThingBeDone()) {
            system.DoIt();
        }
    }
}
</code>```

Both approaches are ok, but both have drawbacks. In Example 1, I'm forcing the consumer to wrap the code in a try-catch for faulty states. These states can be user-triggered so some graceful handling is required. I'm unsure if try-catch for handling user-errors is a good approach.

In Example 2 I'm handing the responsibility of state-checking over to the consumer, opening up for non-descriptive runtime errors. In this example, CanTheThingBeDone() is checked, but when Jimmy enters the team 1 year from now to develop module 2, that might change.

Example 3:

```<code>class System() {
    public bool DoTheThing() {
        if (!CanTheThingBeDone()) return false;
        // Do it
        return true;
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        if (!system.DoTheThing()) ProduceSomeErrorMessage();
    }
}
</code>```

Now in this example, I avoid try-catch for user errors and prevent the actual Do-code to be executed if invalid state, while ensuring the check-code is run only once. But I feel I'm breaking some naming/coding principle when the method is both performing check and modifying class state (I'm pretty sure it even has a name).

As a fourth example, I could envision a combination of #1 & #2 where both the consumer and DoTheThing calls CanTheThingBeDone, but then we're doing the work twice.

To sum up - I can't seem to find a best approach. Anyone have a better idea than mine, or suggestions on how to tweak one of these approaches for a better result?

答:
Use the first example whenever possible. This way it's near impossible to forget the check or to forget to handle the error. Also, such a method may return values without resorting to out-arguments.

Why shouldn't I use #2 or #3? Because it is too easy for a Consumer to ignore the error, e.g. when the programmer is unfamiliar with System's API. The #2 is especially bad because there is no way to find out whether the operation completed successfully.

If you cannot use the exception system for some reason (e.g. you're writing C which doesn't have one, or you are abstaining from exceptions for performance reasons), then I'd suggest a combination of #2 and #3: You return an error code, but if a programmer knows what he's doing, he may omit any error checks. But you should also allow the programmer to explicitly insert the checks beforehand.

Don't think too hard about what an elegant solution would look like: first, try to find a robust approach.


答:
Use references and static analysis tools to avoid production code overload with trivial checking.

Always handle real (as opposed to imaginary) unexpected conditions.  The handling should crash development/debug builds but it should log message and handle the problem in production builds.

Pack crash/log request into short macro. Say 'soft_err()' is more than enough: there is no point in elaborated messages: it would not happen often enough to justify the typing, file-name and line number will be enough to debug issues from the field and for development builds there will be core-dumps.

Note: because handling of unexpected conditions would not happen often it is OK for it to be relatively expensive: say call back-end function to log or crash instead of relying on macros, make back-end functions installed at link time to adapt code to various environments etc.

The combined benefits far outweigh the run-time cost of checking.

Title: Fail-fast paradigm overheads


答:
You're missing a vital point - it's not an either or scenario.

You only need to check "untrusted" parameters. In general, this means the borders of your public interface. If you have a chain of public functions that call other public functions and so on, yes, you'll need to check the input multiple times. You also maybe need to revisit your design to properly abstract and encapsulate things that maybe don't need to be public.

Another spot where this occurs is working with components that can fail (like databases or network connections). If a network connection fails, you don't just pass null back up the call stack, you identify it early and throw an exception or otherwise abort. There's no need to check the return value all the way up the stack.

Title: Fail-fast paradigm overheads


答:
The ISP (interface segregation principle) says that no client should be forced to depend on methods it does not use. The benefits are multiple and clear. Your approach totally respects the ISP, and that's good.

A different approach also respecting the ISP is, for example, create an interface per each method (or set of methods with a high cohesion) and then have a single class implementing all those interfaces. Whether this is or not a better solution depends on the scenario. The benefit of this is, when using dependency injection, you could have a client with diferent collaborators (one per each interface) but in the end all the collaborators will point to the same object instance.

By the way, you said

I find myself instantiating each class

, these classes seem to be services (and thus stateless). Have you thought about making them singletons?


问:
What's the best way to explain branching (of source code) to a client?
The situation is that a client requested a number of changes about 9 months ago which they then put on hold with them half done.  They've now requested more changes without having made up their mind to proceed with the first set of changes.  The two sets of changes will require alterations to the same code modules.

I've been tasked with explaining why them not making a decision about the first set of changes (either finish them or bin them) may incur additional costs (essentially because the changes would need to be made to a branch then if they proceed with the first set of changes we'd have to merge them to the trunk - which will be messy - and retest them).

The question I have is this:

How best to explain branching of code to a non-technical client?

答:
You have an 'A' train with several cars carrying thousands of boxes. After 9 months you decided to create another train on siding called 'A-b' filled with a similar load to train 'A', but some boxes and train cars have been added and some removed.

The train 'A' keeps running down the track and no one has decided if they want the 'A+b' train. A detour is being considered. Train 'A' is going to have to unload some boxes and load some others and the 'A' train would be renamed 'A+c'.

The railroad must ask the customer to make some decisions on what shipment they want.

Forget about 'A+b', unload all the
cars and eat the loading costs.

Have the 'A+b' train catch up to and
replace the 'A' train before the
detour and create train 'A+b+c' train.

Let the 'A' train make the detour becoming the
'A+c' train and then have the 'A+b' train
catchup and then reconfigure train 'A+c' and become '(A+c)(A+b)'

(A+c)(A+b) will cost more and take longer due to all the loading, unloading, and figuring out how to fit the new order configuration on the train.


问:
Preventing some downsides of a static class
Here is my situation. I have implemented the accepted .NET 4.0 answer in this question, which is working.

However, my codebase is quite large and as responsible for this code I've started getting inquiries regarding this solution. I've been asked if there are no easier ways of accomplishing the same thing, and if there is any way to shorten the usage.

In almost all cases, this class is used to get or set a single property only. This favors other solutions, since the usage ends up like this: new UserSessionData().CustomerNumber = 123;

The closest thing I have is a class (static or not) with static members and methods, like this:

```<code>public static class UserSessionData
{
    public static Dictionary<string, string> AsDictionary()
    {
        return typeof(UserSessionData).GetProperties()
                   .ToDictionary(p => p.Name, p => p.GetValue(null, null) as string);
    }
    private static string Get(Expression<Func<string>> e)
    {
        var me = e.Body as MemberExpression;
        return ExternalInterfaceClass.Get(me.Member.Name);
    }
    private static void Set(Expression<Func<string>> e, string value)
    {
        var me = e.Body as MemberExpression;
        ExternalInterfaceClass.Set(me.Member.Name, value);
    }

    public static string CustomerNumber {
        get { return Get(() => CustomerNumber); }
        set { Set(() => CustomerNumber, value); }
    }

    // ... and hundreds more properties similar to "CustomerNumber"
}
</code>```

This feels like a quite good solution:

It's strongly typed (i.e. I can easily refactor CustomerNumber throughout)

Usage is great (UserSessionData.CustomerNumber = 123;)

The boilerplate is not that ugly - I think it's acceptable

However, there is one issue that I can't wrap my head around. Sometimes we need to be able to use this a little differently, A) as a return type and B) bulk-editing the structure before saving. As for A, I understand that a static class cannot be used as a return type, however I don't know what my alternatives would be in this specific situation?

As for B, I guess that I could delay the actual saving by providing a stated subclass and requiring explicit save, but the usage would be worsened for the normal use case (setting or getting a single property) since every one-liner would have to be followed by a call to the save method.

I thought about creating an interface for the class but interfaces can't define static properties. I'm feeling a little muddled here, help is appreciated. Please provide a minimal code example when presenting your thoughts, if possible - it clarifies the point a lot.

答:
It's not exactly an answer to your question but have you looked into T4 templates?

I get the impression you are manually coding those boilerplate properties. If they do indeed follow an almost identical pattern and you would like strong typing try writing code that generates code...

A T4 allows you to iterate through your items and essentially build up a code file, which will be evaluated as you compile, this would mean as you add/remove items to/from your session data it will add/delete those accessors and keep your code up to date and allow you to only set your design standard in one place and have it auto propagate in a loop across all future properties.

A common example of why/where you would use this would be a roll-your-own ORM systems to map a table to a database table without a huge library if you don't need all the CRUD operations...

OwnerDisplayName: Simeon

OwnerDisplayName: apieceoffruit


问:
Sass File Formating - what problems might are there with the following rules?
For a while now I have been considering the formatting of sass files to maximise their usability by other coders and I think that this would be perfect place to get some feedback on the rules I try to apply when writing a sass file. I am specifically interested in the usability of the source code as it is created and maintained by humans, as well as with the correct creation of css code. Some of these rules could be applied to sass or vanilla css.

The rules I have been honing are as follows:

Start general and get specific. So start with body font size, colour variables, default tag declarations etc. then move through the parts of your site that are common to all pages, then onto the re-usable elements on the site and finally concluding with page specific styles, with the liklihood of cascading re-use and the potential for over-ridden styles increasing as you move through the document(s)

Try to group selectors in a way that matches the distribution of html amongst views. So if I look at widget.view the file or block of a file labeled widget.scss will contain those styles. NB, I specifically do not mean following html sructure with hierarchical sass in this case.

Following on from that. Minimise the amount of hierarchy defined in sass. Only use sassy {} based inheritence when needed.

Group properties into logical sets, so width and height together, font declarations together, rather than everything alphabetically.

Always consider the resulting css file size and be prepared to use classes if necessary instead of mixins, editor snippets or other bloat encourgaing techniques.

Put more than one property per line in certain cases, following on from the logical grouping of elements, meaning more code can be fitted onto a monitor screen without going so far as to make lines too long to read easily. No more than 3/4 properties per line.

Block code in files by indenting all selectors after an introductory comment to make the the left hand side of the file easy to scan and to quickly discover it's contents. Also provide a file map of these blocks at the top of the file if it is large.

Use placemarkers for find operations, such as ^NAVIGATION

Only use classes for styles. And don't be afraid to use classes for specifcity and to make re-use more atomic. [edit for clarity - I don't mean use only classes, I mean use classes instead of IDs]

Use a completely separate set of javascript specific classes for binding functionality to html elements, meaning that either form or function can be swapped out without damaging the other. These classes are not refered to in the css.

Selectors one per line and in alphabetical order as they are arbitrary in name

答:
Most of your points are very obvious and make sense no matter what type of project you're working on.  Speaking from a Sass standpoint, rather than a pure CSS standpoint, some of them make very little sense.

#5 (consider the resulting css file size)

This is a major point that most people don't quite grasp when it comes to using @extend in Sass.  If your mixin is generating a lot of code that can be shared with other selectors, then @extend is a good idea.  If you have lengthy selectors or the code being shared is rather short, using @extend is going to lead to a larger CSS file (see: https://codereview.stackexchange.com/questions/26003/mixin-extend-or-silent-class/27910#27910)

#6 (more than one property per line)

This is purely a style preference and has no impact on the code's performance or reusability.   In my opinion, this only reduces readability of the source.  The generated CSS is going to be formatted according to the chosen output style, so the format of the source is irrelevant (unless you're using SASS syntax where whitespace/indentation matters).

Some of this applies to some of your other formatting specific points, too.

#9 (Only use classes for styles)

If your goal is to be reusable, then you should never use classes.  One of the more commonly asked questions regarding libraries like Bootstrap are "how do I use X with only semantic names" or "how do I get the code for X from this module without also importing the code for Y".  Instead, make good mixins and functions so that users can compose them in ways that make sense for their project.

#10 (separate set of javascript specific classes)

Form follows function.  If what you've got is a toggle, then there is a difference in styling between the opened and closed states.  It does not make sense to make another class just for that.

There are other properties worth considering which may make more sense (both from the JavaScript and CSS side) such as disabled, checked or the use of data-* attributes (eg. data-state="opened").

OwnerDisplayName: ColinSharpe


答:
You should use some variant of #1. Consumers cannot be trusted to check rules to see if something can be run before running something. That adds temporal coupling, even if people remember it.

Ways to improve it:

Lazy - assuming CanSomethingBeDone can never change during the lifetime of the object, you can lazily initialize it so you don't check it every call; just once on first use.

Decorators - You should also probably better separate CanSomethingBeDone from DoSomething, since they are separate responsibilities, which may not change together. A decorator seems like a good approach here. Then you can have a code DoSomething and a decorator that checks the rule before calling its wrapped implementation. This keeps things separate and composable. Though this works best when the consumer shouldn't know about the capability at all.

No-Ops - Depending on your usage, it may be preferable to simply do nothing rather than throw an exception if the consumer can't run DoSomething. This simplifies the call site, especially if the capability is exposed and you expect that DoSomething won't usually be called because it won't be clickable.

Don't expose it - if you've got a composition/plug-in structure, you might be able to hide the entire command when it is unavailable. This though requires a particular architecture and some other constraints that let you know that the plug-in is unavailable early and constantly.

Title: Pattern for costly precondition check before acting

Body:
Let's say I have a method DoTheThing() which requires the precondition-check CanTheThingBeDone() to return true. The latter method is time consuming as it accesses the database.

I'm finding it hard to find a perfect way to perform the precondition check effectively (i.e. once) while maintaining both readability and API integrity. Observe these examples:

Example 1:

```<code>class System() {
    public void DoTheThing() {
        if (!CanTheThingBeDone()) throw new Exception(...);
        // Do it
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        try {
            system.DoTheThing();
        }
        catch (Exception) {
            // Error handling
        }
    }
}
</code>```

Example 2:

```<code>class System() {
    public void DoTheThing() {
        // Do it
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        if (system.CanTheThingBeDone()) {
            system.DoIt();
        }
    }
}
</code>```

Both approaches are ok, but both have drawbacks. In Example 1, I'm forcing the consumer to wrap the code in a try-catch for faulty states. These states can be user-triggered so some graceful handling is required. I'm unsure if try-catch for handling user-errors is a good approach.

In Example 2 I'm handing the responsibility of state-checking over to the consumer, opening up for non-descriptive runtime errors. In this example, CanTheThingBeDone() is checked, but when Jimmy enters the team 1 year from now to develop module 2, that might change.

Example 3:

```<code>class System() {
    public bool DoTheThing() {
        if (!CanTheThingBeDone()) return false;
        // Do it
        return true;
    }

    public bool CanTheThingBeDone() {
        // Some time consuming code
    }
}

class Consumer() {
    public void SomeLargerOperation() {
        if (!system.DoTheThing()) ProduceSomeErrorMessage();
    }
}
</code>```

Now in this example, I avoid try-catch for user errors and prevent the actual Do-code to be executed if invalid state, while ensuring the check-code is run only once. But I feel I'm breaking some naming/coding principle when the method is both performing check and modifying class state (I'm pretty sure it even has a name).

As a fourth example, I could envision a combination of #1 & #2 where both the consumer and DoTheThing calls CanTheThingBeDone, but then we're doing the work twice.

To sum up - I can't seem to find a best approach. Anyone have a better idea than mine, or suggestions on how to tweak one of these approaches for a better result?


问:
How To Know When To Stop Testing?
I know this is a very very basic question. For some software applications there are a large almost infinitely high number of test cases for an application. It is not practical to test all those test cases. How do we decide when to stop testing? (other than "when money runs out"). </p>

答:
When the people that have to sign off on the deploy are satisfied.

or in some cases the majority of the responsible parties are satisfied.

Title: How To Know When To Stop Testing?


问:
How to unit test a missing case in a switch statement where all cases are true
I often use enum types in my code with a switch to apply logic to each type. In these cases it's important that each enum has code implemented.

For example;

```<code>public enum eERROR
{
    REQUIRED,
    DUPLICATE,
    UNKNOWN,
    MISSING_VALUE
}

public void Error(eERROR pError)
{
    switch (pError)
    {
        case eERROR.REQUIRED:
            // ......
            return;
        case eERROR.DUPLICATE:
            // ......
            return;
        case eERROR.MISSING_VALUE:
            // ......
            return;
        case eERROR.UNKNOWN:
            // ......
            return;
    }

    throw new InvalidArgumentException("Unsupported error type");
}
</code>```

At the bottom I've added an exception as a last resort check that a programmer remembered to add any new enum types to the switch statement. If a new type is added to eERROR the exception could be thrown if the code is not updated.

Here is my problem.

The above code generates unit test coverage of only 99% because I can not trigger the exception. I could add a generic unhandled to eERROR and call Error(eERROR.unhandled) just to get 100% coverage, but that feels like a hack to solve something that is not a problem just to get full coverage. I could remove the line but then I don't have the safety check.

Why is 99% a problem? because the code base is so large that any uncovered method doesn't move coverage to 98%. So I always see 99% and don't know if I missed a method or two.

How can I rewrite Error() so that all newly added enums that are not added to the switch will be caught somehow by the programmer, and also be covered by tests. Is there a way of doing it without added a dummy enum?

答: You cannot test code that is intended to be run only in the event of a programming error, because that would imply that your test suite can only run successfully if there is a programming error in the code base! The fact that it's nevertheless useful to write such guards against supposedly impossible cases is one of the reasons why the goal "absolutely 100% code coverage" is not a good goal.


问:
Using unsigned integers in C and C++
I have a very simple question that baffles me for a long time. I am dealing with networks and databases so a lot of data I am dealing with are 32-bit and 64-bit counters (unsigned), 32-bit and 64-bit identification ids (also do not have meaningful mapping for sign). I am practically never deal with any real word matter that could be expressed as a negative number.

Me and my co-workers routinely use unsigned types like uint32_t and uint64_t for these matters and because it happens so often we also use them for array indexes and other common integer uses.

At the same time various coding guides I am reading (e.g. Google) discourage use of unsigned integer types, and as far as I know neither Java nor Scala have unsigned integer types.

So, I could not figure out what is the right thing to do: using signed values in our environment would be very inconvenient, at the same time coding guides to insist on doing exactly this.

答:
First of all, the Google C++ coding guideline is not a very good one to follow: it shuns things like exceptions, boost, etc which are staples of modern C++. Secondly, just because a certain guideline works for company X doesn't mean it will be the right fit for you. I would continue using unsigned types, as you have a good need for them.

A decent rule of thumb for C++ is: prefer int unless you have a good reason to use something else.

Title: Using unsigned integers in C and C++


答:
@DieterLucking is absolutely right but I wanted to add on to what he said.  That rule doesn't apply to just C++ but to just about any language as well including managed ones.

The idea of fail fast is that you do not go overboard and provide all kinds of checking and exception handling to "try" to keep running when there are unexpected error conditions because you are under the impression my product is 24/7 it has to run.  Being able to run 24/7 is a great requirement and we can all strive for that, but the reality is that the product needs to run correctly 24/7.  But software does have an occasional bug, some are recoverable but many aren't.  In those cases, you might as well crash, because a server process that crashes, goes offline for 20 seconds and gets restarted is still a better alternative than a server process that keeps running for hours but handles incoming requests incorrectly for hours until a human restarts it.

So what does that mean for you as a developer?  If there are unexpected circumstances, don't check for them (you will never anticipate them all even if you try) and simply let your code crash.  When that happens, you will be able to capture a crash dump and determine the exact location of the crash and often the root cause.

And before someone reads this, gets all fired up and starts commenting how I advocate writing code that crashes and how that makes me a terrible developer, here's a little story.

An engineer comes to me for help. Says he spent a full week working on one customer problem and he is out of ideas. They can duplicate the problem by following an exact series of steps, which requires opening dialog A, clicking a bunch of buttons, then closing that dialog, and going to a completely different part of the application.  If you do those steps exactly, your app crashes but he can't figure out why.

So together we take a look at the crash dump and see that processes heap has been corrupted, but there is no indication where or how that happened.  After a whole bunch of digging we found code in dialog A that looked like this:

```<code>try {
    ... do some work
}
catch( ... ) {
    ... not even a log statement here ...
}
</code>```

So the code in dialog A was going off the deep end and doing some really bad stuff. Instead of crashing early with a stack trace that shows the exact problem the developer decided that crashes are bad and app must stay running.  So instead, the app would crash 15 min to 4 hours later in a completely random place when you were doing a completely harmless action.  That developer didn't help anyone with his protected code.

Title: Fail-fast paradigm overheads

Body:
@DieterLucking is absolutely right but I wanted to add on to what he said.  That rule doesn't apply to just C++ but to just about any language as well including managed ones.

The idea of fail fast is that you do not go overboard and provide all kinds of checking and exception handling to "try" to keep running when there are unexpected error conditions because you are under the impression my product is 24/7 it has to run.  Being able to run 24/7 is a great requirement and we can all strive for that, but the reality is that the product needs to run correctly 24/7.  But software does have an occasional bug, some are recoverable but many aren't.  In those cases, you might as well crash, because a server process that crashes, goes offline for 20 seconds and gets restarted is still a better alternative than a server process that keeps running for hours but handles incoming requests incorrectly for hours until a human restarts it.

So what does that mean for you as a developer?  If there are unexpected circumstances, don't check for them (you will never anticipate them all even if you try) and simply let your code crash.  When that happens, you will be able to capture a crash dump and determine the exact location of the crash and often the root cause.

And before someone reads this, gets all fired up and starts commenting how I advocate writing code that crashes and how that makes me a terrible developer, here's a little story.

An engineer comes to me for help. Says he spent a full week working on one customer problem and he is out of ideas. They can duplicate the problem by following an exact series of steps, which requires opening dialog A, clicking a bunch of buttons, then closing that dialog, and going to a completely different part of the application.  If you do those steps exactly, your app crashes but he can't figure out why.

So together we take a look at the crash dump and see that processes heap has been corrupted, but there is no indication where or how that happened.  After a whole bunch of digging we found code in dialog A that looked like this:

try {
    ... do some work
}
catch( ... ) {
    ... not even a log statement here ...
}

So the code in dialog A was going off the deep end and doing some really bad stuff. Instead of crashing early with a stack trace that shows the exact problem the developer decided that crashes are bad and app must stay running.  So instead, the app would crash 15 min to 4 hours later in a completely random place when you were doing a completely harmless action.  That developer didn't help anyone with his protected code.


问:
Python - assert vs if & return
I am writing a script that does something to a text file (what it does is irrelevant for my question though). So before I do something to the file I want to check if the file exists. I can do this, no problem, but the issue is more that of aesthetics.

Here is my code, implementing the same thing in two different ways.

```<code>def modify_file(filename):
    assert os.path.isfile(filename), 'file does NOT exist.'

Traceback (most recent call last):
  File "clean_files.py", line 15, in <module>
    print(clean_file('tes3t.txt'))
  File "clean_files.py", line 8, in clean_file
    assert os.path.isfile(filename), 'file does NOT exist.'
AssertionError: file does NOT exist.
</code>```

or:

```<code>def modify_file(filename):
    if not os.path.isfile(filename):
        return 'file does NOT exist.'

file does NOT exist.
</code>```

The first method produces an output that is mostly trivial, the only thing I care about is that the file does not exist.

The second method returns a string, it is simple.

My questions is: which method is better for letting the user know that the file does not exist? Using the assert method seems somehow more pythonic.

答:
You'd go with a third option instead: use raise and a specific exception. This can be one of the built-in exceptions, or you can create a custom exception for the job.

In this case, I'd use IOError, but a ValueError might also fit:

```<code>def modify_file(filename):
    if not os.path.isfile(filename):
        raise IOError('file does NOT exist.')
</code>```

Using a specific exception allows you to raise other exceptions for different exceptional circumstances, and lets the caller handle the exception gracefully.

Of course, many file operations (like open()) themselves raise OSError already; explicitly first testing if the file exists may be redundant here.

Don't use assert; if you run python with the -O flag, all assertions are stripped from the code.

Title: Python - assert vs if & return

Body:
You'd go with a third option instead: use raise and a specific exception. This can be one of the built-in exceptions, or you can create a custom exception for the job.

In this case, I'd use IOError, but a ValueError might also fit:

def modify_file(filename):
    if not os.path.isfile(filename):
        raise IOError('file does NOT exist.')

Using a specific exception allows you to raise other exceptions for different exceptional circumstances, and lets the caller handle the exception gracefully.

Of course, many file operations (like open()) themselves raise OSError already; explicitly first testing if the file exists may be redundant here.

Don't use assert; if you run python with the -O flag, all assertions are stripped from the code.


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答:
Optional parameters are just fine

Typically the justification is either that a) you know you have a lot of possible arguments for your method but you don't want to overload for fear of clutering your API, or b) when you don't know all the possible arguments  but you don't want to force your user to provide an array. In each case optional parameters come to the rescue in a neat and elegant way.

Here are some examples:

1. You want to avoid overloading and don't want to specify an array

Take a look at printf() from C, Perl, Java etc. It's a great example of the power of optional parameters.

For example:

```<code>printf("I want %d %s %s",1,"chocolate","biccies");

printf("I want %d banana",1);
</code>```

No overloading, no arrays, simple and intuitive (once you've grasped the standard string format codes). Some IDEs will even tell you if your format string does not match your optional parameters.

2. You want to allow the use of defaults and keep them hidden from the user of the method

sendEmail("test@example.org");

The sendEmail method detects that various essential values are missing and fills them in using defined defaults (subject, body, cc, bcc etc). The API is kept clean, yet flexible.

A note on too many parameters

However, as others have stated, having too many mandatory parameters to a method indicates that you probably have something wrong with your design. This is particularly true if they share the same type since they can be switched by the developer by accident leading to strange results at runtime:

```<code>String myMethod(String x, String y, String z, String a, int b, String c, int d) {}
</code>```

is an ideal candidate for the Introduce Parameter Object refactoring to create

```<code>String myMethod(ParameterObject po) {}

class ParameterObject {
  // Left as public for clarity
  public String x;
  public String y;
  ... etc

}
</code>```

This in turn can lead to a better design based on a Factory pattern with a provided specification as the parameter object.

Body:
Optional parameters are just fine

Typically the justification is either that a) you know you have a lot of possible arguments for your method but you don't want to overload for fear of clutering your API, or b) when you don't know all the possible arguments  but you don't want to force your user to provide an array. In each case optional parameters come to the rescue in a neat and elegant way.

Here are some examples:

1. You want to avoid overloading and don't want to specify an array

Take a look at printf() from C, Perl, Java etc. It's a great example of the power of optional parameters.

For example:

printf("I want %d %s %s",1,"chocolate","biccies");

printf("I want %d banana",1);

No overloading, no arrays, simple and intuitive (once you've grasped the standard string format codes). Some IDEs will even tell you if your format string does not match your optional parameters.

2. You want to allow the use of defaults and keep them hidden from the user of the method

sendEmail("test@example.org");

The sendEmail method detects that various essential values are missing and fills them in using defined defaults (subject, body, cc, bcc etc). The API is kept clean, yet flexible.

A note on too many parameters

However, as others have stated, having too many mandatory parameters to a method indicates that you probably have something wrong with your design. This is particularly true if they share the same type since they can be switched by the developer by accident leading to strange results at runtime:

String myMethod(String x, String y, String z, String a, int b, String c, int d) {}

is an ideal candidate for the Introduce Parameter Object refactoring to create

String myMethod(ParameterObject po) {}

class ParameterObject {
  // Left as public for clarity
  public String x;
  public String y;
  ... etc

}

This in turn can lead to a better design based on a Factory pattern with a provided specification as the parameter object.


答:
Depending on your language, you should just be able to pass in a garbage value to the Error constructor. Most languages just use integers for enum values. In pseudo-code:</p>

```<code>e = new Error(eError -1)
>> InvalidArgumentException: Unsupported error type
</code>```

Title: How to unit test a missing case in a switch statement where all cases are true

Body:
I often use enum types in my code with a switch to apply logic to each type. In these cases it's important that each enum has code implemented.

For example;

```<code>public enum eERROR
{
    REQUIRED,
    DUPLICATE,
    UNKNOWN,
    MISSING_VALUE
}

public void Error(eERROR pError)
{
    switch (pError)
    {
        case eERROR.REQUIRED:
            // ......
            return;
        case eERROR.DUPLICATE:
            // ......
            return;
        case eERROR.MISSING_VALUE:
            // ......
            return;
        case eERROR.UNKNOWN:
            // ......
            return;
    }

    throw new InvalidArgumentException("Unsupported error type");
}
</code>```

At the bottom I've added an exception as a last resort check that a programmer remembered to add any new enum types to the switch statement. If a new type is added to eERROR the exception could be thrown if the code is not updated.

Here is my problem.

The above code generates unit test coverage of only 99% because I can not trigger the exception. I could add a generic unhandled to eERROR and call Error(eERROR.unhandled) just to get 100% coverage, but that feels like a hack to solve something that is not a problem just to get full coverage. I could remove the line but then I don't have the safety check.

Why is 99% a problem? because the code base is so large that any uncovered method doesn't move coverage to 98%. So I always see 99% and don't know if I missed a method or two.

How can I rewrite Error() so that all newly added enums that are not added to the switch will be caught somehow by the programmer, and also be covered by tests. Is there a way of doing it without added a dummy enum?

Body:
Depending on your language, you should just be able to pass in a garbage value to the Error constructor. Most languages just use integers for enum values. In pseudo-code:

e = new Error(eError -1)
>> InvalidArgumentException: Unsupported error type


答:
There are two schools of thought on this, and neither will ever agree.

The first argues that there are some concepts that are inherently unsigned - such as array indexes.  It makes no sense to use signed numbers for those as it may lead to errors.  It also can impose un-necessary limits on things - an array that uses signed 32-bit indexes can only access 2 billion entries, while switching to unsigned 32-bit numbers allows 4 billion entries.

The second argues that in any program that uses unsigned numbers, sooner or later you will end up doing mixed signed-unsigned arithmetic.  This can give strange and unexpected results: casting a large unsigned value to signed gives a negative number, and conversely casting a negative number to unsigned gives a large positive one.  This can be a big source of errors.

Title: Using unsigned integers in C and C++

Body:
I have a very simple question that baffles me for a long time. I am dealing with networks and databases so a lot of data I am dealing with are 32-bit and 64-bit counters (unsigned), 32-bit and 64-bit identification ids (also do not have meaningful mapping for sign). I am practically never deal with any real word matter that could be expressed as a negative number.

Me and my co-workers routinely use unsigned types like uint32_t and uint64_t for these matters and because it happens so often we also use them for array indexes and other common integer uses.

At the same time various coding guides I am reading (e.g. Google) discourage use of unsigned integer types, and as far as I know neither Java nor Scala have unsigned integer types.

So, I could not figure out what is the right thing to do: using signed values in our environment would be very inconvenient, at the same time coding guides to insist on doing exactly this.


答:
There is one rule I like: When in doubt, create an object. C# is an OOP language, not functional after all. So thinking in objects is much better than thinking in methods.

```<code>public abstract class ExpensiveOperation
{
    bool wasTested = false;
    bool canBeDone = false;

    protected abstract bool Precondition();
    protected abstract void DoExecute();

    public bool CanExecute()
    {
        if (!wasTested)
        {
            canBeDone = Precondition();
            wasTested = true;
        }
        return canBeDone;
    }

    public void Execute()
    {
        if (!CanExecute())
            throw new Exception("Cannot execute");

        DoExecute();
    }
}
</code>```

Then you just derive this for your custom operation with precondition. It has many good properties:

It encapsulates the operation with it's precondition

Ensures the precondition is called and operation cannot be executed if precondition fails

Ensures the precondition is called only once no matter what caller does.

Give caller option to check if it can be executed if necessary

You just supply the code for precondition and operation, no need to create more code

Ensures the caller cannot bypass this precondition logic

Body:
There is one rule I like: When in doubt, create an object. C# is an OOP language, not functional after all. So thinking in objects is much better than thinking in methods.

public abstract class ExpensiveOperation
{
    bool wasTested = false;
    bool canBeDone = false;

    protected abstract bool Precondition();
    protected abstract void DoExecute();

    public bool CanExecute()
    {
        if (!wasTested)
        {
            canBeDone = Precondition();
            wasTested = true;
        }
        return canBeDone;
    }

    public void Execute()
    {
        if (!CanExecute())
            throw new Exception("Cannot execute");

        DoExecute();
    }
}

Then you just derive this for your custom operation with precondition. It has many good properties:

It encapsulates the operation with it's precondition

Ensures the precondition is called and operation cannot be executed if precondition fails

Ensures the precondition is called only once no matter what caller does.

Give caller option to check if it can be executed if necessary

You just supply the code for precondition and operation, no need to create more code

Ensures the caller cannot bypass this precondition logic


问:
Working with shader code
I am starting my first project in OpenGL/GLSL and I was wondering, how do you work with code of shaders?

Because it needs to be const char and syntax higlighting shows everything in the same color (as string) and so its difficult to navigate in code.

```<code>const char *shader = ..."void main()\n"...;
</code>```

Do you edit the code and then add quotation marks or do you just write it with quotation marks from the start? Thanks

edit: using VS2012

答:
One thing you can do to make including shader code in C(++) source files more convenient is defining a macro like this:

```<code>#define GLSL(x) "#version #150\n" #x
</code>```

Example:

```<code>const char* shader = GLSL(
    out vec4 outColor;
    void main() {
        outColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
);
</code>```

This will give you better formatting and basic C-style syntax highlighting:

Note that new lines will be ignored, so any preprocessor statements must be explicit.

Title: Working with shader code

Body:
One thing you can do to make including shader code in C(++) source files more convenient is defining a macro like this:

#define GLSL(x) "#version #150\n" #x

Example:

const char* shader = GLSL(
    out vec4 outColor;
    void main() {
        outColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
);

This will give you better formatting and basic C-style syntax highlighting:

Note that new lines will be ignored, so any preprocessor statements must be explicit.


答:
What about this, then you can test with null as invalid value?

```<code>public void Error(eERROR pError)
{
    if (pError != null) {
        switch (pError)
        {
            // ......
        }
    }

    throw new InvalidArgumentException("Unsupported error type: " + pError);
}
</code>```

Body:
What about this, then you can test with null as invalid value?

public void Error(eERROR pError)
{
    if (pError != null) {
        switch (pError)
        {
            // ......
        }
    }

    throw new InvalidArgumentException("Unsupported error type: " + pError);
}


问:
Best way to rename existing unique field names in database?
I have a database table that contains id, filename, userId

id is unique identifier

filename should also be unique

table may contain >10000 records

When a user uploads a file it should be entered in database with given
  rules:

If there is no record with same filename, it should be added as it is (Ex. foobar.pdf)

If there is record with same filename, it should be added as uploadedName(2).ext (foobar(2).pdf)

If there are n records with same base filename (foobar), it should be added as uploadedName(n+1).ext (foobar(20).pdf)

Now if foobar(2).pdf is uploaded, it should be added as foobar(2)(2).pdf & so on

This pattern needs to be followed because the file is already being
  uploaded at client side using ajax before sending the details to
  server and the file hosting service follows the above rules to name
  the files.

My solution:

maintain a file that contains all the names and the number of times
it has occurred.

if a filename that exists in file is entered, increase occurrence count and new name is generated, else add to it to file

if the new name generated is in database, add it to file and generate new name

答:
If the original filename is not significant then do as others have suggested and generate a synthetic name -- a UUID would be a good candidate or use a sequence like your primary key. If the name is significant, i.e. you want to store it, then simply add a column to make it possible for the user to distinguish between duplicates possible and meaningful, and to reduce/eliminate duplicates. For instance, a timestamp indicating when the file was uploaded.

It's not entirely clear to me what you're asking -- your title has a question, but your post does not. If you're looking to update the column name of a table look into alter table -- it's simple. If you're looking for how to massage existing data then see above. Otherwise you'll need to rephrase your request so it's a bit clearer.

Anyway, hope this helps!


答:
One question do you need the catch all clause at all? If a new element is added to the Enum will the type checker catch that for you? I know that in Erlang if you wrote something like that case statement then dialyzer would tell you flat out that there is no way that the error case could ever match via static analysis .

Maybe I am just spoiled by very good tools that don't exist in all languages.


问:
Are classes with only a single (public) method a problem?
I am currently working on a software project that performs compression and indexing on video surveillance footage. The compression works by splitting background and foreground objects, then saving the background as a static image, and the foreground as a sprite.

Recently, I have embarked on reviewing some of the classes that I have designed for the project.

I noticed that there are many classes that only have a single public method. Some of these classes are:

VideoCompressor (with a compress method that takes in an input video of type RawVideo and returns an output video of type CompressedVideo).

VideoSplitter (with a split method that takes in an input video of type RawVideo and returns a vector of 2 output videos, each of type RawVideo).

VideoIndexer (with an index method that takes in an input video of type RawVideo and returns a video index of type VideoIndex).

I find myself instantiating each class just to make calls like VideoCompressor.compress(...), VideoSplitter.split(...), VideoIndexer.index(...).

On the surface, I do think the class names are sufficiently descriptive of their intended function, and they are actually nouns. Correspondingly, their methods are also verbs.

Is this actually a problem?

答:
This is a sign that you want to pass functions as arguments to other functions. I'm guessing your language (Java?) doesn't support it; if that's the case, it's not so much a failing in your design as it is a shortcoming in your language of choice. This is one of the biggest problems with languages that insist that everything must be a class.

If you aren't actually passing these faux-functions around then you just want a free/static function.


答:
As a developer who applies test driven development from day to day I believe the question should be the other way around. When you cannot test the code there is no reason for that code.
You may extend the enum by inheritance (if possible) or use a mock instead to trigger a specific case.</p>


答:
A database table should include creation and modification templates when either of the following is true:

The table represents a primary record of some user supplied activity.  If the user does X , and you have both a Table_X and a Table_Y which are one-to-many children of Table_X, Table_Y is not a primary record and so doesn't need the extra fields.

When you have a permanent, temporary, or recurring need for system tracking.  If you have a need to check that Table_Y only gets updated when Table_X is updated, the extra tracking fields can assist.

Note that neither of these are exclusive; you can go ahead and add them everywhere by default, and omit only when needed for performance tuning.

Title: When should a database table use timestamps?

Body:
First a note, I thought maybe this question belonged in the database exchange, but I think it is more broadly related to a programming solution as a whole than to databases. Will move to database exchange if people think thats the best one.

I was wondering when a database table should have a created and updated timestamp added?

The first obvious answer is that if any business logic needs to know when something was updated (like a transaction completion date etc) then it must go in.

But what about non business logic cases? For example I can think of scenarios where it would be really useful to know the date time that rows changed to help with fault finding e.g. some business logic is failing and looking at the related database rows its possible to identify that one row is being update before another row which is causing the error.

With this use case, it would make sense to give every table an update and create timestamp (except for maybe the most trivial enum tables that wouldn't be updated by any part of the application).

Giving every table a timestamp is surely a great way to quickly bog down a database (although could be wrong).

So when should a database table use create and update timestamps?


问:
Nulls in every type and checked exceptions in Java?
I know that null being added to every type in Java is a source of much frustration regarding the language's type system. At the same time I generally hear complaining about checked exceptions - that they clutter interfaces, encourage exception swallowing, etc. It seems to me like null inhabiting every type is a way around the language - like I want the type of this to be X, but it's actually X or null; it just doesn't look like that and is easy to forget. Don't checked exceptions provide a way for the type of something to be X or throws Exception instead of it appearing to just be X? It provides an in-code way to specify how something can fail.

Nulls in every type and unchecked exceptions seem like they are dual concepts, but one is scorned and the other praised. Why is that?

答:
I wouldn't call null and checked exceptions dual concepts; in fact, they're kind of the same thing in disguise (more on this later). Signaling failure in a return value and unchecked exceptions are dual concepts. Returning null is one way to signal failure in the return value, but it subverts the language's type system. You've already caught on to that fact - you can never have the type of just Strings, you must live with the type of Strings-and-null.

The correct approach to using the return value is to get rid of null and use a separate type (usually called Option or Maybe) that represents the concept of "a value of type T, or Nothing". An Option X is not an X - you can't assign one to the other, and you have to explicitly inspect the Option and handle both cases. You can't simply forget that the function could fail to return a value.

Maybe works well when failures are common and can be handled immediately. It doesn't work so well when failures are rare and the immediate caller can't do anything meaningful about it. When failure can only be handled further up the stack, you have to return Maybe all the way up - if you get a value, proceed, and if you don't, return Nothing, over and over again until you get to the point where you can actually handle the error. Imagine if division didn't throw an exception and instead returned Maybe Double - what a pain!

Not only is this clumsy, it forces everything between the handler and the error to know about the possibility of failure and change its return type to Maybe. This gets in the way when you're writing functions that take other functions as arguments. Sometimes you want to pass a function that could theoretically fail, but you've either ensured this won't be the case, or you can't do anything about it if it did. Unchecked exceptions come to the rescue here, because they do the forwarding of the error automatically and anything in between can be blissfully ignorant of the possibility of failure. If your only option were Maybe and checked exceptions, you'd be out of luck, because the possibility of failure is encoded in the function's return type and that makes it incompatible with the type of function you're expecting.

The problem with checked exceptions is that they're not fit for either purpose. When the error has to be handled further up, you force all code between the handler and the failure to reflect the possibility of failure in its signature. When the error can be handled immediately, you get all the benefits of Maybe - you can't forget to handle it - but it's clumsier to use than a simple if/switch! So it's kind of a clumsy Maybe in exception's clothings.