问:
What should this interface contain?
I am creating a schema for Doctrine but first I'm creating interfaces, abstract classes (models) which will be extended by the entities.

I have a PresentationInterface which contain getter and setters for presentation info, ParticipantInterface which contains the same (firstname, lastname, email).

Both have their abstract classes, Presentation and Participant which implement the getter and setters and also contain mapping information for those fields. They may contain some utlity methods which are not defined in the interface but are needed inside the getter and setters for processing data.

The entities are Presentation, Attendee and Presenter. Attendee extends from the Participant model, and Presenter from Attendee. Now to differentiate I'm using Doctrine's single table inheritance type with a discriminator column called is_presenter which is mapped at Attendee entity.

Basically, a Presenter is able to create a Presentation which thereafter is joined by Attendees.

My question is, should isPresenter have been defined in ParticipantInterface? Is the way I've done it worse or fine? If I had left it in the interface, I couldn't use it as a discriminator anyway, but from a logical point of view should it have been in the interface or maybe in another called PresenterParticipantInterface?

答:
I have no idea what Doctrine is, but from what you are describing looks like ORM.

Regardless, I will speak from SOLID and software design perspective.

I would apply ISP(Interface Segregation Principle from SOLIDs) and have a number interfaces: IAttendee, IParticipant and IPresenter with their own respective methods.

So you could have variations of objects that conform to specifi set of interfaces:

```<code>public class Attendee extends Participant implements IAttendee { }
public class Presenter extends Attendee implements IPresenter {}
public class Auditor extends Attendee implmenets IAuditor {}
</code>```

Use interfaces to your advantage, don't just meaninglessly create them because you were told to do so. Mix and match them :)

Title: What should this interface contain?

Body:
I have no idea what Doctrine is, but from what you are describing looks like ORM.

Regardless, I will speak from SOLID and software design perspective.

I would apply ISP(Interface Segregation Principle from SOLIDs) and have a number interfaces: IAttendee, IParticipant and IPresenter with their own respective methods.

So you could have variations of objects that conform to specifi set of interfaces:

public class Attendee extends Participant implements IAttendee { }
public class Presenter extends Attendee implements IPresenter {}
public class Auditor extends Attendee implmenets IAuditor {}

Use interfaces to your advantage, don't just meaninglessly create them because you were told to do so. Mix and match them :)


问:
Is this too much work for a Gateway to do?
I'm writing a Gateway class that wraps access to a web service which provides information about a player's item inventory in a video game. This web service returns a variety of information, however I do not need to use all of it.

The only thing I need to know from the web service is if a given game item is present in the player's inventory. This logic would be simple to implement: I would iterate over the player's items, trying to find a match. However, herein lies my primary concern: is this too much work for a Gateway to do? Would it be better practice to have the Gateway merely extract the list of items, and then handle the checking elsewhere? This would seem silly to me, because my program really only cares about the existence of a particular item and I don't really need a list of every item.

答:
Let's go back to good old SOLID principals. Currently, your Gateway is:

Providing integration with Web Interface AND

Checking for an item in users inventory.

You broke Single Responsibility principal :) Is it terrible? No, not really, but, trust me, it's much easier to correct it now, while you don't have a large application instead of correcting things like this later.

So, I would do it this way:

```<code>// Inventory service.
public class InventoryService
{
    private IWebInventoryGateway _gateway;

    // Injecting a dependency here to decouple classes
    public InventoryService(IWebInventoryGateway gateway)
    {

    }

    // Method that does one an only thing! Checking if the item is in the inventory.
    public bool ContainsItems(string item, int playerId) {
        var inventory = _gateway.GetInventory(playerId);

        // do the list checking here...

        return true;
    }
}

// Gateway interface so you could swap your gateways without affecting any other classes. Decoupling here.
public interface IWebInventoryGateway
{
    IEnumerable<string> GetInventory(int playerId);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's go back to good old SOLID principals. Currently, your Gateway is:

Providing integration with Web Interface AND

Checking for an item in users inventory.

You broke Single Responsibility principal :) Is it terrible? No, not really, but, trust me, it's much easier to correct it now, while you don't have a large application instead of correcting things like this later.

So, I would do it this way:

// Inventory service.
public class InventoryService
{
    private IWebInventoryGateway _gateway;

    // Injecting a dependency here to decouple classes
    public InventoryService(IWebInventoryGateway gateway)
    {

    }

    // Method that does one an only thing! Checking if the item is in the inventory.
    public bool ContainsItems(string item, int playerId) {
        var inventory = _gateway.GetInventory(playerId);

        // do the list checking here...

        return true;
    }
}

// Gateway interface so you could swap your gateways without affecting any other classes. Decoupling here.
public interface IWebInventoryGateway
{
    IEnumerable<string> GetInventory(int playerId);
}


问:
Does it break SRP to have concerns of data handling and object mapping inside a single class, as part of the DataMapper pattern?
Summary

I want to look into separating the concern of "creating a populated object from database", to use inside my application.  DataMapper pattern seems to be doing just that for me.

DataMapper pattern definition:  http://martinfowler.com/eaaCatalog/dataMapper.html

However, inside the DataMapper pattern itself there are concerns of

object management - creation, population, validation (maybe), return to caller, destruction, saving, updating etc.

loading of the data acquired from the database (i.e. construction of SQL, sending SQL to native DB functions, receiving DB data resource, or in PHP's case an associative array of data)

mapping of the loaded data from the database into the object's variables (schema-to-object translation, hydration, etc).

My goal as far as my application goes is to start with "I want data, give me data", and DataMapper going "here it is, all ready for ya.  And not just the data you wanted, but a whole object, already populated with the data, & mapped properly from the DB schema too!".  ("Wow, thanks DataMapper!")

Question:

Can DataMapper pattern contain all of the above concerns inside a single class, or must it split each concern into their own separate classes?

Details & Some Code

Below I will focus on concerns of "data" and "object creation & population".  Considering concepts such as separation of concerns, dependency injection, and object oriented programming best practices, is it appropriate for a DataMapper pattern to contain concern of data handling?   Can data concern (i.e. SQL) and concern of creating-n-populating-an-object coexist inside one class?

In example below, I have SQL (aka data concern) in my DataMapper class

class MyProductMapper
{
    function getProduct()
    {
        $sql = "SELECT name FROM product limit 1";
        $result = db_query($sql);
        $data = db_fetch_array($result);

        $product = new MyProduct($data);

        return $product;
    }
}
```

<p><strong>Should Data Concern be separated?</strong></p>

<p>Consider code below as an alternative to code above
(SQL extracted out of DataMapper and moved into its own data class):</p>

```//class that concerns itself with receiving some data
//creating an object, and populating that object with the data
//returning that object
class MyProductMapper
{
    function getProduct()
    {
        $data = (new ProductData())->getNameData();
        $product = new MyProduct($data);

        // return product to the caller
        return $product;
    }
}

//class concerns itself with data retrieval functionality
class ProductData
{
    function getNameData()
    {
        $sql = "SELECT name FROM product limit 1";
        $result = db_query($sql);
        $dataFromDB = db_fetch_array($result);//array('name'=>"ABC-1234");
        return $dataFromDB;
    }
}
```

I have separated the Data retrieval from object creation/object-population.  Should data concern be separated from concern of of the DataMapper class, or can it coexist with others inside the same class, or does it matter at all, and one way is just as good as another?

答:
The code sample #2 you provided is preferable in my opinion.

What if tomorrow you want to have CachedProductData, you would only update product data class, or rather introduce another layer.

If you have both classes merged like in example 1, you would be updating both responsibilities.

So, Single Responsibility Principal would be broken if you choose example #1.


答:
I've never seen the point of a class that only queries the database and returns an array (or DataSet or DataTable for those in .NET). The mapping of columns in a database to properties or fields on an object belongs in its own class, not in the constructor. The whole point of a data mapper is to decouple the database schema from the object model. By passing $data in as a constructor argument to MyProduct you have embedded the database schema in your object model.

A more clear and straight forward pattern is to create a repository class that deals exclusively with your object model. It would have a data mapper object that maps columns to fields in your object model.

First, your mapper:

```<code>class DataMapper {
    public function toMyProduct($data) {
        $product = new MyProduct();

        foreach ($data as $key => $value) {
            // Simple property injection:
            $product->$key = $value;

            // Or setter injection
            $setter = 'set' . ucfirst($key);
            $product->$setter($value);
        }

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

Then your repository class, which would take the mapper as a constructor argument:

```<code>class MyProductRepository {
    private $mapper;

    public function __construct(DataMapper $mapper) {
        $this->mapper = $mapper;
    }

    public function find($id) {
        $sql = "...";
        // build parameterized query
        $result = db_query($sql);
        $data = db_fetch_array($result);//array('name'=>"ABC-1234");

        return $this->mapper->toMyProduct($data);
    }

    public function update(MyProduct $product) {
        // build parameterized query for UPDATE statement
    }
}
</code>```

The true cleanliness of this approach becomes apparent when you start to use these classes together:

```<code>$mapper = new DataMapper();
$products = new MyProductRepository($mapper);
$product = $products->find(10);
echo $product->getName();
</code>```

You can take it one step further and implement the Unit of Work pattern using a database context object, that wraps all the repository classes for each table in the database:

```<code>class DbContext {
    public __construct() {
        $this->mapper = new DataMapper();
        $this->products = new MyProductRepository($this->mapper);
    }

    public $products;

    public function commit() {
        // issue COMMIT command to the database
    }

    public function rollback() {
        // issue ROLLBACK command to the database
    }
}
</code>```

Now your code becomes even cleaner, with the added benefit of transaction management:

```<code>$db = new DbContext();

try {
    $product = $db->products->find(10);
    // do stuff with $product

    $db->products->update($product);
    $db->commit();
} catch (Exception $ex) {
    $db->rollback();

    throw $ex;
}
</code>```

If you really need a method that returns the raw array from the database, that becomes just another method on your repository class:

```<code>class MyProductRepository {
    private $mapper;

    public __construct(DataMapper $mapper) {
        $this->mapper = mapper;
    }

    public function find($id) {
        $data = $this->findData($id);

        return $this->mapper->toMyProduct($data);
    }

    public function findData($id) {
        $sql = "...";
        // build parameterized query
        $result = db_query($sql);
        $data = db_fetch_array($result);//array('name'=>"ABC-1234");

        return $data;
    }

    public function update(MyProduct $product) {
        // build parameterized query for UPDATE statement
    }
}
</code>```

Title: Does it break SRP to have concerns of data handling and object mapping inside a single class, as part of the DataMapper pattern?

Body:
Summary

I want to look into separating the concern of "creating a populated object from database", to use inside my application.  DataMapper pattern seems to be doing just that for me.

DataMapper pattern definition:  http://martinfowler.com/eaaCatalog/dataMapper.html

However, inside the DataMapper pattern itself there are concerns of

object management - creation, population, validation (maybe), return to caller, destruction, saving, updating etc.

loading of the data acquired from the database (i.e. construction of SQL, sending SQL to native DB functions, receiving DB data resource, or in PHP's case an associative array of data)

mapping of the loaded data from the database into the object's variables (schema-to-object translation, hydration, etc).

My goal as far as my application goes is to start with "I want data, give me data", and DataMapper going "here it is, all ready for ya.  And not just the data you wanted, but a whole object, already populated with the data, & mapped properly from the DB schema too!".  ("Wow, thanks DataMapper!")

Question:

Can DataMapper pattern contain all of the above concerns inside a single class, or must it split each concern into their own separate classes?

Details & Some Code

Below I will focus on concerns of "data" and "object creation & population".  Considering concepts such as separation of concerns, dependency injection, and object oriented programming best practices, is it appropriate for a DataMapper pattern to contain concern of data handling?   Can data concern (i.e. SQL) and concern of creating-n-populating-an-object coexist inside one class?

In example below, I have SQL (aka data concern) in my DataMapper class

class MyProductMapper
{
    function getProduct()
    {
        $sql = "SELECT name FROM product limit 1";
        $result = db_query($sql);
        $data = db_fetch_array($result);

        $product = new MyProduct($data);

        return $product;
    }
}
```

<p><strong>Should Data Concern be separated?</strong></p>

<p>Consider code below as an alternative to code above
(SQL extracted out of DataMapper and moved into its own data class):</p>

```//class that concerns itself with receiving some data
//creating an object, and populating that object with the data
//returning that object
class MyProductMapper
{
    function getProduct()
    {
        $data = (new ProductData())->getNameData();
        $product = new MyProduct($data);

        // return product to the caller
        return $product;
    }
}

//class concerns itself with data retrieval functionality
class ProductData
{
    function getNameData()
    {
        $sql = "SELECT name FROM product limit 1";
        $result = db_query($sql);
        $dataFromDB = db_fetch_array($result);//array('name'=>"ABC-1234");
        return $dataFromDB;
    }
}
```

I have separated the Data retrieval from object creation/object-population.  Should data concern be separated from concern of of the DataMapper class, or can it coexist with others inside the same class, or does it matter at all, and one way is just as good as another?

Body:
I've never seen the point of a class that only queries the database and returns an array (or DataSet or DataTable for those in .NET). The mapping of columns in a database to properties or fields on an object belongs in its own class, not in the constructor. The whole point of a data mapper is to decouple the database schema from the object model. By passing $data in as a constructor argument to MyProduct you have embedded the database schema in your object model.

A more clear and straight forward pattern is to create a repository class that deals exclusively with your object model. It would have a data mapper object that maps columns to fields in your object model.

First, your mapper:

class DataMapper {
    public function toMyProduct($data) {
        $product = new MyProduct();

        foreach ($data as $key => $value) {
            // Simple property injection:
            $product->$key = $value;

            // Or setter injection
            $setter = 'set' . ucfirst($key);
            $product->$setter($value);
        }

        return $product;
    }
}

Then your repository class, which would take the mapper as a constructor argument:

class MyProductRepository {
    private $mapper;

    public function __construct(DataMapper $mapper) {
        $this->mapper = $mapper;
    }

    public function find($id) {
        $sql = "...";
        // build parameterized query
        $result = db_query($sql);
        $data = db_fetch_array($result);//array('name'=>"ABC-1234");

        return $this->mapper->toMyProduct($data);
    }

    public function update(MyProduct $product) {
        // build parameterized query for UPDATE statement
    }
}

The true cleanliness of this approach becomes apparent when you start to use these classes together:

$mapper = new DataMapper();
$products = new MyProductRepository($mapper);
$product = $products->find(10);
echo $product->getName();

You can take it one step further and implement the Unit of Work pattern using a database context object, that wraps all the repository classes for each table in the database:

class DbContext {
    public __construct() {
        $this->mapper = new DataMapper();
        $this->products = new MyProductRepository($this->mapper);
    }

    public $products;

    public function commit() {
        // issue COMMIT command to the database
    }

    public function rollback() {
        // issue ROLLBACK command to the database
    }
}

Now your code becomes even cleaner, with the added benefit of transaction management:

$db = new DbContext();

try {
    $product = $db->products->find(10);
    // do stuff with $product

    $db->products->update($product);
    $db->commit();
} catch (Exception $ex) {
    $db->rollback();

    throw $ex;
}

If you really need a method that returns the raw array from the database, that becomes just another method on your repository class:

class MyProductRepository {
    private $mapper;

    public __construct(DataMapper $mapper) {
        $this->mapper = mapper;
    }

    public function find($id) {
        $data = $this->findData($id);

        return $this->mapper->toMyProduct($data);
    }

    public function findData($id) {
        $sql = "...";
        // build parameterized query
        $result = db_query($sql);
        $data = db_fetch_array($result);//array('name'=>"ABC-1234");

        return $data;
    }

    public function update(MyProduct $product) {
        // build parameterized query for UPDATE statement
    }
}


问:
What to do about complex business logic based on many options
To preface, I think this problem would be easier to understand if I gave an example: How does a complex tax evaluation application manage multiple tax laws and personal situations?

I inherited a web application which has a lot of business logic lodged in the views. This logic controls page flow and control visualization. The gist of this logic is based on properties of a context such as: what state was the action taken, who is the client, what type of task, and many more. example of such logic:

```<code>if task.state == "WA" then goto view1
else if task.type == "Wash Windows" && task.clientid == 5 then goto windowWashview2
</code>```

feature requests come in all the time to add new tasks, with new rules.
I've explored Domain Specific Languages briefly.

Any suggestions?

答:
First and foremeost, you seriously need to isolate business logic from Views. You don't need to do it all at once, but with new feature requests, you really need to workout a better distribution of roles in your application.

Secondly, Strategy Design Pattern is exactly what you need in your application:

The idea of the pattern is to eliminate hard dependencies and let the components decide what to do with their tasks. For example, you might have a Router class that basing on what state it is, will return the right view to present to the user.

You might have JobBasedCalculator class that would base calculation of the location and job type it supports. And every JobCalculator class should be treated as that, just SOME JobCalculator class regardless if it's  an IT job, Civic Job, etc... they should all conform to the same interface is what I mean.

Another pattern to look at is State Object. Might prove to be useful if you have so many logical decisions  to make based on selections, but if app is large, this can be an anti-pattern as well.


问:
What can procs and lambdas do that functions can't in ruby
I've been working in Ruby for the last couple weeks, and I've come to the subject of procs, lambdas and blocks.  After reading a fair share of examples from a variety of sources, I don't how they're much different from small, specialized functions.  It's entirely possible that the examples I've read aren't showing the power behind procs and lambdas.

```<code>def zero_function(x)
    x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
end

zero_lambda = lambda {|x|
  x = x.to_s
   if x.length == 1
    return x = "0" + x
   else
    return x
   end
}

zero_proc = Proc.new {|x|
  x = x.to_s
   if x.length == 1
    puts x = "0" + x
   else
    puts x
   end
}

puts zero_function(4)
puts zero_lambda.call(3)
zero_proc.call(2)
</code>```

This function, proc, and lambda do the exact same thing, just slightly different.  Is there any reason to choose one over another?

答:
The other big difference between procs, methods and lambdas is how they deal with break and return.

Basically, a return in a Proc will jump out of any enclosing method as well, and a return from a lambda will only exit the lambda.

A break from a Proc tries to break out of an enclosing iteration (if there's no iteration, you'll get an error), while a break from a lambda is just like a return.

More details here: http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/


问:
Try to find a word in the dictionary that has most letters given
I recently came across an algorithm design problem that I'd like some help with:

Given some letters, for example a,e,o,g,z,k,l,j,w,n and a dictionary of words. Find a word in the dictionary that has most letters.

My first attempt:

Let us assume that the dictionary is in a tree. Start by finding the permutations of the given letters, here we could be using recursion, we can prune the recursion tree, by checking the letters in the dictionary. and we maintain a variable which holds the largest string formed till now.

How is this solution? Is there a better one?

答:
I'd like to add to SF's solution a bit. Not sure if I am correct in my analysis, but anyway:

If your preprocessing is free (considering search will be done enough times) you can preprocess each word in a dict by producing for it an entity like the index SF mentioned. So each word becomes a number like

```<code>01000100011101.... (up to the last letter a set of words can consist of)
</code>```

where each 1 represents if the word has this letter or not (let's skip the case where it has double or more for simplicity).

You can further arrange this transformed dict by the amount of different letters the word has, to start searching with ones that contain most letters and be able to cut off search early once you enter the range that can't posibly have more matches than you already have.

When iterating over each word of a dictionary (now reduced to numbers) you simply XOR this number with the number produced from the set of the letters you are looking for and calculate its hamming weight(the number of 1s) which is essentially what you are looking for.

https://en.wikipedia.org/wiki/Hamming_weight

As the size of input is always constant (the size of the alphabet instead of variable word size) it can be done efficiently with publicly available algos. This way you wont have to compare letters one by one. Dealing with double/triple letters can be done by augmenting structures I suppose.

Body:
I'd like to add to SF's solution a bit. Not sure if I am correct in my analysis, but anyway:

If your preprocessing is free (considering search will be done enough times) you can preprocess each word in a dict by producing for it an entity like the index SF mentioned. So each word becomes a number like

01000100011101.... (up to the last letter a set of words can consist of)

where each 1 represents if the word has this letter or not (let's skip the case where it has double or more for simplicity).

You can further arrange this transformed dict by the amount of different letters the word has, to start searching with ones that contain most letters and be able to cut off search early once you enter the range that can't posibly have more matches than you already have.

When iterating over each word of a dictionary (now reduced to numbers) you simply XOR this number with the number produced from the set of the letters you are looking for and calculate its hamming weight(the number of 1s) which is essentially what you are looking for.

https://en.wikipedia.org/wiki/Hamming_weight

As the size of input is always constant (the size of the alphabet instead of variable word size) it can be done efficiently with publicly available algos. This way you wont have to compare letters one by one. Dealing with double/triple letters can be done by augmenting structures I suppose.


问:
Is automatically generating passwords during registration a good idea?
I'm developing a registration system for a project I'm working on.

Since users tend not to sign up if the process is too long, I've thought to require (at least initially) just their email, where I would send them their automatically generated password (and that would also allow me to verify their email address). That would also prevent them from choosing a weak password in order to complete the registration fast.

I haven't found any downsides so far, but I'm afraid there are some as I've never seen a site using this system.

Is that a good idea?

PS: of course I'm also implementing sign up via Facebook and other similar services to allow people to sign up fast without the need of a password, but many may want to choose the classic sign up for privacy concerns or because they don't use any of those services.

答:
Honestly, there is not much value to it.

1) Most people use their own password that they remember. If they do, then making them change their password will take longer than filling up an extra field during registration.

The benefit of your system may be that by then the user is registered so you'll not lose it.

2) If they use a password manager it is easier to just make the password manager fill in their preferred username and a random password with 1 click than having to edit the file afterwards and inserting your generated password (likely to take 3 or 4 clicks extra).

3) The current system is so widely used that some people will be confused by the lacking of a password field (like I did with google, but it's google and I trust it).


答:
The problem is that a password should appear in plain text as rarely as possible.

In your case, the password appears in plain text in an e-mail. This has several drawbacks:

If the account of the person is compromised, the hacker gets access to your website as well.

If there is a malicious man in the middle, he can access the password with ease.

Moreover:

Auto-generated passwords are difficult to remember, so instead of making the life easier for your users, you are making it more difficult and at the same time encourage to write down the password on a Post-it, which may not be the best thing in terms of security.

This is why most websites which generate such passwords during registration make them one-use passwords. In other words, the user receives an e-mail with a random password, but once he uses it to log in, the website immediately asks for the new password chosen by the user, preventing the three drawbacks mentioned above.

Title: Is automatically generating passwords during registration a good idea?

Body:
I'm developing a registration system for a project I'm working on.

Since users tend not to sign up if the process is too long, I've thought to require (at least initially) just their email, where I would send them their automatically generated password (and that would also allow me to verify their email address). That would also prevent them from choosing a weak password in order to complete the registration fast.

I haven't found any downsides so far, but I'm afraid there are some as I've never seen a site using this system.

Is that a good idea?

PS: of course I'm also implementing sign up via Facebook and other similar services to allow people to sign up fast without the need of a password, but many may want to choose the classic sign up for privacy concerns or because they don't use any of those services.


问:
Updating a video's view count. Should this happen client-side or server-side?
I built an iOS app similar to Vine, where a user can scroll a feed of videos that auto play. All of these video have a View_Count field in the backend to keep track of how many times the video has been viewed.

Right now the way I have it set up, is as soon as the user starts watching the video, I increase the View_Count locally on their phone so they can see it tick up, and then I make a call to the backend server with the following steps:

Request video object to grab most recent View_Count (the one on the user's phone will be different as many people are watching these videos at the same time)

Increase View_Count by 1.

Post updated View_Count to server.

I am mostly a front end/iOS guy, so I'm not sure if this is a correct assumption, but I feel like the above steps should NOT be happening on the user's phone. I feel like it is not only using too much of the user's data plan, but also my gut tells me that this type of logic is not supposed to be on the client-side.

Am I correct in assuming this?

All of our video's are stored on AWS using s3 buckets and are being accessed via CDN URL's. I feel like every time an s3/Cloudfront CDN URL is accessed, that AWS should ping my server and increase the View_Count by 1 for that video, but really I have nothing to go off of but my gut instinct because I've never done something like this before.

Am I on the right track at all with these assumptions, or am I approaching this the wrong way?

答:
The scenario itself: "a user views a video should increase view count" is a client side activity resulting in backend data changes. It is initiated by the user using the client app, so it is okay to put the code that initiates and increases of view count in the client app.

However, here are some other/different ideas to consider:

Keep using the client side code to increase view count, but queue these actions somewhere offline and only sync them periodically.

Proxy the actual URL of the video with a url that redirects to the actual video and increases the view count (completely backend code here)

Use a CDN that can provide the view count statistic out of the box.

And I'm sure there plenty of different ideas out there.


问:
Rich client persistence without a database
We have a pretty sizable .NET rich client app that currently uses nHibernate and Firebird embedded for persistence. Due to the nature of the app, we need to load the entire database into memory when the file is loaded, so we get all the costs of an ORM without many of the benefits. The main benefit we do get is the ability to write upgrade code to transition the structure of the data between versions.

We're finding that this setup is both slow and memory intensive (unsurprisingly, given that we're not using it as intended). We could move to a document/KVP DB, but again, given that we're not doing any on-demand loading or searching, it doesn't feel like the right solution.

I've toyed with the idea of binary serialization and somehow archiving off the 'persistence' namespace so that we could load an old format, but it seems a bit of a convoluted approach to what I would think would be a common problem.

What are our options?

答:
For info, I went down the binary serialization path, with a light-weight mapping structure between the domain and the serializer. Initial, unoptimized tests have it at about 40% faster than nHibernate.

I'm hoping to get approval to open source it - if I do I'll edit this answer with the details.


问:
Aggregation vs Composition
I understand what composition is in OOP, but I am not able to get a clear idea of what Aggregation is. Can someone explain?</p>

答:
Composition(mixture) is a way to combine simple objects or data types into more complex ones. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true

```<code>╔═══════════╦═════════════════════════╦═══════════════════════╗
║           ║       Aggregation       ║      Composition      ║
╠═══════════╬═════════════════════════╬═══════════════════════╣
║ Life time ║ Have their own lifetime ║ Owner's life time     ║
║ Relation  ║ Has                     ║ part-of               ║
║ Example   ║ Car has driver          ║ Engine is part of Car ║
╚═══════════╩═════════════════════════╩═══════════════════════╝
</code>```

Both denotes relationship between object and only differ in their strength.

UML notations for different kind of dependency between two classes

Composition : Since Engine is part-of Car, relationship between them is Composition. Here is how they are implemented between Java classes.

```<code>public class Car {
    //final will make sure engine is initialized
    private final Engine engine;

    public Car(){
       engine  = new Engine();
    }
}

class Engine {
    private String type;
}
</code>```

Aggregation : Since Organization has Person as employees, relationship between them is Aggregation. Here is how they look like in terms of Java classes

```<code>public class Organization {
    private List employees;
}

public class Person {
    private String name;
}
</code>```

Source

Title: Aggregation vs Composition

Body:
Composition(mixture) is a way to combine simple objects or data types into more complex ones. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true

╔═══════════╦═════════════════════════╦═══════════════════════╗
║           ║       Aggregation       ║      Composition      ║
╠═══════════╬═════════════════════════╬═══════════════════════╣
║ Life time ║ Have their own lifetime ║ Owner's life time     ║
║ Relation  ║ Has                     ║ part-of               ║
║ Example   ║ Car has driver          ║ Engine is part of Car ║
╚═══════════╩═════════════════════════╩═══════════════════════╝

Both denotes relationship between object and only differ in their strength.

UML notations for different kind of dependency between two classes

Composition : Since Engine is part-of Car, relationship between them is Composition. Here is how they are implemented between Java classes.

public class Car {
    //final will make sure engine is initialized
    private final Engine engine;

    public Car(){
       engine  = new Engine();
    }
}

class Engine {
    private String type;
}

Aggregation : Since Organization has Person as employees, relationship between them is Aggregation. Here is how they look like in terms of Java classes

public class Organization {
    private List employees;
}

public class Person {
    private String name;
}

Source


问:
Best way to synchronize data between two different databases
I have to implement data synchronization between two big databases which have completely different structures. Basically, I need to grap some data about products in different tables in the first database and re-arrange them for other tables in the second database.

Creating my products on the first time is not very complicated. But I'm looking for a way to update some specific data - not all data - about each product.

Obviously, there are a few issues that make this tricky.

I'm not allowed to do anything on the source database apart select queries.

On the target database, I can do usual queries (select, update, insert, create) but I can't modify the existing structure/tables.

Target and source db have completely different structures, tables are not the same at all, therefore data really have to be rearranged - comparing tables won't work.

Target database uses a MySQL server - source may be DB2.

There are no "updated time" fields anywhere.

So the whole process needs to be done in a single Python (ideally) script.

I think about creating a hash for each product, based on the fields to update in the target database: md5( code + description + supplier + around 10 other fields). A new hash based on the same data will be created on a daily basis from the source database. I will store all hashes in a single table ( item code, current_hash, old_hash ) for performances purpose. Then compare and update the product if the new hash is different from the old one.

There are around 500 000 products so I'm a bit worried about performances.

Is it the good way to go?

答:
The data sync would be much better and faster, if it can be done on the basis of some kind of delta identifier or flag. Basically, you should update the target db data rows only when it is out of sync with the source db.

In SQL server db, you can take the help of the Checksum fn also to build the delta based identifier.

You should develop a SQL based job to get invoked at a certain time of the day or night to get this sql logic fired. It is better to run it as a nightly SQL job, when the db usage is very low. If the delta of the source and the target db records does not match, then pull those records only. But the downside would be to calculate the checksum of the source data rows every time and then compare it with the target data.

If you have a column like "LastModifiedDate" in the source db tables, then you can skip the checksum approach. This way, your evaluation will be executed on the date based column and takes less time in comparison to the checksum approach.


问:
How to create a 2D array at runtime in Ada?

In Ada programming, What is a best practice way to create a 2D array of a size that is specified by the user?

I'm teaching myself Ada for work (after many years of C programming), and I'm having difficulty understanding how to create an array of a size that is only known at runtime...

My simple program needs to do the following.

Ask the user to type in two numbers, for the width (X) and height
(Y) of a 2 dimensional character array.

Use these values as the upper bounds of the array (0..X-1, 0..Y-1).

Initialise the array with zeroes.

After quite a bit of googling I think I'm almost there, if I hard code the array to a fixed size then the program works fine, but I'd like to get the array sized as per the user's desire.

My full program is as follows, it doesn't compile, but I hope it is enough to demonstrate what I'm trying to do.

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters; use Ada.Characters;

procedure test is
  type Two_Dimensional_Char_Array is array (Integer range <>, Integer range <>) of character;
  --grid : Two_Dimensional_Char_Array (0..59, 0..29) := (others => (others => ' '));
  grid : Two_Dimensional_Char_Array;

  procedure Draw_Grid(scr : Two_Dimensional_Char_Array) is
    X, Y : Integer := 0;
  begin
    Put("Width? ");
    Get(X);

    Put("Height? ");
    Get(Y);

    declare
      grid : Two_Dimensional_Char_Array(0..X-1, 0..Y-1);
    begin
      grid := (others => (others => 0));
    end;

    Put("+");
    for X in scr'First(1)..scr'Last(1) loop
      Put("-");
    end loop;
    Put_Line("+");

    for Y in scr'First(2)..scr'Last(2) loop
      Put("|");
      for X in scr'First(1)..scr'Last(1) loop
        Put(scr(X, Y));
      end loop;
      Put_Line("|");
    end loop;

    Put("+");
    for X in scr'First(1)..scr'Last(1) loop
      Put("-");
    end loop;
    Put_Line("+");
  end Draw_Grid;

begin
  grid(0,0) := 'a';
  grid(0,1) := 'b';
  grid(1,1) := 'c';
  grid(20,10) := 'd';
  grid(59,29) := 'X';
  Draw_Grid(grid);
end test;
</code>```

答:
The best practice is to use "constructor" function.

While the type can be unconstrained, the actual object has to posses some compile time bounds on size (unless you allocate it on heap).

You should create additional function for creating this array. Here is how I modified your code and works just fine (do note that I changed indices to be 1 based, as I hate 0 based array indices).

Additionally in your sample code you tried to initialize your Grid with Integers... (despite the fact that Grid is 2D array of Character)

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure test is
  type Two_Dimensional_Char_Array is
    array (Integer range <>, Integer range <>) of Character;

  -- "constructor" function.
  function Create_Grid return Two_Dimensional_Char_Array
  is
    X, Y: Natural := 0;
  begin
    Put ("Width? ");
    Get (X);

    Put ("Height? ");
    Get (Y);

    declare
      Grid: constant Two_Dimensional_Char_Array (1 .. X, 1 .. Y) :=
        (others => (others => ' '));
    begin
      return Grid;
    end;
  end Create_Grid;

  procedure Draw_Grid(scr : Two_Dimensional_Char_Array) is
  begin
    Put ("+");
    for X in scr'Range (1) loop
      Put ("-");
    end loop;
    Put_Line ("+");

    for Y in scr'Range (2) loop
      Put ("|");
      for X in scr'Range (1) loop
        Put (scr (X, Y));
      end loop;
      Put_Line ("|");
    end loop;

    Put ("+");
    for X in scr'Range (1) loop
      Put ("-");
    end loop;
    Put_Line ("+");
  end Draw_Grid;

  -- Create grid at runtime using function.
  Grid: Two_Dimensional_Char_Array := Create_Grid;

begin
  Grid (1,1)    := 'a';
  Grid (1,2)    := 'b';
  Grid (2,2)    := 'c';
  Grid (21,11)  := 'd';
  Grid (60,30)  := 'X';
  Draw_Grid (Grid);
end test;
</code>```

In addition there is nice attribute in Ada: 'Range - used in for loops when you are iterating over entire range (which is just a shortcut for 'First .. 'Last)

PS: Why are you, C programmers, so averse of using spaces in code? It makes it hard to read [as in: scr'First(1)..scr'Last(1)].

Body:
The best practice is to use "constructor" function.

While the type can be unconstrained, the actual object has to posses some compile time bounds on size (unless you allocate it on heap).

You should create additional function for creating this array. Here is how I modified your code and works just fine (do note that I changed indices to be 1 based, as I hate 0 based array indices).

Additionally in your sample code you tried to initialize your Grid with Integers... (despite the fact that Grid is 2D array of Character)

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure test is
  type Two_Dimensional_Char_Array is
    array (Integer range <>, Integer range <>) of Character;

  -- "constructor" function.
  function Create_Grid return Two_Dimensional_Char_Array
  is
    X, Y: Natural := 0;
  begin
    Put ("Width? ");
    Get (X);

    Put ("Height? ");
    Get (Y);

    declare
      Grid: constant Two_Dimensional_Char_Array (1 .. X, 1 .. Y) :=
        (others => (others => ' '));
    begin
      return Grid;
    end;
  end Create_Grid;

  procedure Draw_Grid(scr : Two_Dimensional_Char_Array) is
  begin
    Put ("+");
    for X in scr'Range (1) loop
      Put ("-");
    end loop;
    Put_Line ("+");

    for Y in scr'Range (2) loop
      Put ("|");
      for X in scr'Range (1) loop
        Put (scr (X, Y));
      end loop;
      Put_Line ("|");
    end loop;

    Put ("+");
    for X in scr'Range (1) loop
      Put ("-");
    end loop;
    Put_Line ("+");
  end Draw_Grid;

  -- Create grid at runtime using function.
  Grid: Two_Dimensional_Char_Array := Create_Grid;

begin
  Grid (1,1)    := 'a';
  Grid (1,2)    := 'b';
  Grid (2,2)    := 'c';
  Grid (21,11)  := 'd';
  Grid (60,30)  := 'X';
  Draw_Grid (Grid);
end test;

In addition there is nice attribute in Ada: 'Range - used in for loops when you are iterating over entire range (which is just a shortcut for 'First .. 'Last)

PS: Why are you, C programmers, so averse of using spaces in code? It makes it hard to read [as in: scr'First(1)..scr'Last(1)].


答:
Here is a revised version:

 with Ada.Text_IO; use Ada.Text_IO;
 with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
 with Ada.Characters; use Ada.Characters;

 procedure test is
    type Two_Dimensional_Char_Array is
      --  Natural range seems more appropriate
      array (Natural range <>, Natural range <>) of Character;

   procedure Draw_Grid(grid : Two_Dimensional_Char_Array) is
   begin
      Put("+");
      for X in grid'First(1)..grid'Last(1) loop
         Put("-");
      end loop;
      Put_Line("+");

      for Y in grid'First(2)..grid'Last(2) loop
         Put("|");
         for X in grid'First(1)..grid'Last(1) loop
            Put(grid(X, Y));
         end loop;
         Put_Line("|");
      end loop;

      Put("+");
      for X in grid'First(1)..grid'Last(1) loop
         Put("-");
      end loop;
      Put_Line("+");
   end Draw_Grid;

   X, Y : Natural;

 begin
    Put("Width? ");
    Get(X);

    Put("Height? ");
    Get(Y);

    declare
       grid : Two_Dimensional_Char_Array(0..X-1, 0..Y-1) := (others => (others => ' '));
    begin
       --  grid is only visible in this block

       grid(0,0) := 'a';
       grid(0,1) := 'b';
       grid(1,1) := 'c';
       grid(20,10) := 'd';
       grid(59,29) := 'X';
       Draw_Grid(grid);
    end;
 end test;
```

Draw_Grid only draws the grid. It does not need to know the actual sizes, because the code you wrote uses 'First and 'Last attributes, which is good. Maybe it would be possible to shorten that a bit with grid'Range, but I did not try.

I change the indice type to Natural, because you don't expect to have negative indices (that could be possible, but 0..X-1 suggests you don't want that).

X, Y are declared in the scope of the main procedure, and initialized first by prompting the user.

Then, grid is declared in a sub-block (it won't be accessible outside of this scope), with the given dimensions.

Finally, populate the grid and draw it.

Note that a runtime Constraint_Error is raised when the dimensions are not large enough: you assume you can set a value at (59,29).

Title: How to create a 2D array at runtime in Ada?

Body:
In Ada programming, What is a best practice way to create a 2D array of a size that is specified by the user?

I'm teaching myself Ada for work (after many years of C programming), and I'm having difficulty understanding how to create an array of a size that is only known at runtime...

My simple program needs to do the following.

Ask the user to type in two numbers, for the width (X) and height
(Y) of a 2 dimensional character array.

Use these values as the upper bounds of the array (0..X-1, 0..Y-1).

Initialise the array with zeroes.

After quite a bit of googling I think I'm almost there, if I hard code the array to a fixed size then the program works fine, but I'd like to get the array sized as per the user's desire.

My full program is as follows, it doesn't compile, but I hope it is enough to demonstrate what I'm trying to do.

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Characters; use Ada.Characters;

procedure test is
  type Two_Dimensional_Char_Array is array (Integer range <>, Integer range <>) of character;
  --grid : Two_Dimensional_Char_Array (0..59, 0..29) := (others => (others => ' '));
  grid : Two_Dimensional_Char_Array;

  procedure Draw_Grid(scr : Two_Dimensional_Char_Array) is
    X, Y : Integer := 0;
  begin
    Put("Width? ");
    Get(X);

    Put("Height? ");
    Get(Y);

    declare
      grid : Two_Dimensional_Char_Array(0..X-1, 0..Y-1);
    begin
      grid := (others => (others => 0));
    end;

    Put("+");
    for X in scr'First(1)..scr'Last(1) loop
      Put("-");
    end loop;
    Put_Line("+");

    for Y in scr'First(2)..scr'Last(2) loop
      Put("|");
      for X in scr'First(1)..scr'Last(1) loop
        Put(scr(X, Y));
      end loop;
      Put_Line("|");
    end loop;

    Put("+");
    for X in scr'First(1)..scr'Last(1) loop
      Put("-");
    end loop;
    Put_Line("+");
  end Draw_Grid;

begin
  grid(0,0) := 'a';
  grid(0,1) := 'b';
  grid(1,1) := 'c';
  grid(20,10) := 'd';
  grid(59,29) := 'X';
  Draw_Grid(grid);
end test;
</code>```

Body:
Here is a revised version:

 with Ada.Text_IO; use Ada.Text_IO;
 with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
 with Ada.Characters; use Ada.Characters;

 procedure test is
    type Two_Dimensional_Char_Array is
      --  Natural range seems more appropriate
      array (Natural range <>, Natural range <>) of Character;

   procedure Draw_Grid(grid : Two_Dimensional_Char_Array) is
   begin
      Put("+");
      for X in grid'First(1)..grid'Last(1) loop
         Put("-");
      end loop;
      Put_Line("+");

      for Y in grid'First(2)..grid'Last(2) loop
         Put("|");
         for X in grid'First(1)..grid'Last(1) loop
            Put(grid(X, Y));
         end loop;
         Put_Line("|");
      end loop;

      Put("+");
      for X in grid'First(1)..grid'Last(1) loop
         Put("-");
      end loop;
      Put_Line("+");
   end Draw_Grid;

   X, Y : Natural;

 begin
    Put("Width? ");
    Get(X);

    Put("Height? ");
    Get(Y);

    declare
       grid : Two_Dimensional_Char_Array(0..X-1, 0..Y-1) := (others => (others => ' '));
    begin
       --  grid is only visible in this block

       grid(0,0) := 'a';
       grid(0,1) := 'b';
       grid(1,1) := 'c';
       grid(20,10) := 'd';
       grid(59,29) := 'X';
       Draw_Grid(grid);
    end;
 end test;

Draw_Grid only draws the grid. It does not need to know the actual sizes, because the code you wrote uses 'First and 'Last attributes, which is good. Maybe it would be possible to shorten that a bit with grid'Range, but I did not try.

I change the indice type to Natural, because you don't expect to have negative indices (that could be possible, but 0..X-1 suggests you don't want that).

X, Y are declared in the scope of the main procedure, and initialized first by prompting the user.

Then, grid is declared in a sub-block (it won't be accessible outside of this scope), with the given dimensions.

Finally, populate the grid and draw it.

Note that a runtime Constraint_Error is raised when the dimensions are not large enough: you assume you can set a value at (59,29).


问:
Recommended HTTP status code for "plan limit exceeded" response
I'm designing a REST API for a project where users are always on one of several "plans" - each plan defines some resource limits, such as the max number of users an account may have or the max number of data they may upload. Once one of these limits is reached, users can upgrade their plans (essentially pay up) to get more resources.

I want to return a special status code indicating a situation where the action cannot be performed due to account resource limits, and upgrading the plan will resolve this - for example if a user uses 100% of their storage capacity and try to upload an additional file, they will get this response.

The candidates are, IMHO:

403 Forbidden - however, I would like to distinguish between this case and other cases where the user simply lacks the permission to perform this action.

401 Unauthorized - not a good idea, we're using this for authentication related problems.

402 Payment Required - makes kind of sense but I'm worried about using a non-standard yet reserved status code

Something even less standard like 423 Locked as its unlikely we'll use it for anything else in the future

Another option is to go with something very standard such as 403 but indicate the specifics of the error in the response body.

I'm wondering which approach you believe would (a) work best in the long run and (b) would stick more nicely to RESTful principles.

答:
I think 403 is the only reasonable response, though 405 Method Not Allowed or 409 Conflict might be acceptable, I don't think either are as good as 403 which states:

The server understood the request, but is refusing to fulfill it.
  Authorization will not help and the request SHOULD NOT be repeated.
  If the request method was not HEAD and the server wishes to make
  public why the request has not been fulfilled, it SHOULD describe the
  reason for the refusal in the entity

If you return a 403 error, it'll include some information on why the resource was denied - invalid permission is only the most common case, exceeded limits isn't much different - you don't have permission because your limit was exceeded.


问:
Open Source code bounties
I have a library for R (open source statistics package) mapped out on paper. I have started coding the different functions but I realize that I don't have the time needed to finish this in a reasonable amount of time. I know I can just throw the code up on a repo and call for others to help fill in the blanks. But I'd like to incentivize things a bit. I'm thinking about putting a bounty on each function of, say, $5-$20. There's no way that $20 would be a fair return on time for a developer to code each function. But my thought is that the cash (or Amazon gift certificates) would be an inventive for people to actually work on the project. And it would allow me to put higher bounties on the functions I am most interested in.

I have a few questions related to this:

Good idea?

I going to make
the development work faster, or
slower? I've read Predictably
Irrational and I'm concerned
that by offering menial pay for
functions I might actually
disincentive developers.

Are
there sites devoted to this type of
activity? Can you recommend one based on personal experience?

Would you recommend a totally different approach? I'm open to ideas!

答:
Not a good idea, in my mind. None of the OSS programmers I know would respond to such a bounty.

So, what does incentivize people? According to Dan Pink people are motivated by:

Autonomy

Mastery

Purpose

Then to attract good programmers, find a way to provide some or all of those items.

A second approach that can be done concurrently with the first is to display a home page that tracks the progress of the project, showing the status of each of the functions along with the person who provided the function that first passed the unit tests (you do have tests, right?).

Finally, it's been my experience that a compelling project doesn't need much help in attracting contributors. Take a look at what you are doing and if you are having a hard time attracting and keeping programmers to work on it, think about what that is telling you about the usefulness of your project.

ContentLicense: CC BY-SA 2.5

Title: Open Source code bounties


答: WebDAV uses HTTP 507 Insufficient Storage for this and includes an additional error code for quota exceeded in the request body, to distinguish it from other kinds of storage limitations.

Title: Recommended HTTP status code for "plan limit exceeded" response

Body:
I'm designing a REST API for a project where users are always on one of several "plans" - each plan defines some resource limits, such as the max number of users an account may have or the max number of data they may upload. Once one of these limits is reached, users can upgrade their plans (essentially pay up) to get more resources.

I want to return a special status code indicating a situation where the action cannot be performed due to account resource limits, and upgrading the plan will resolve this - for example if a user uses 100% of their storage capacity and try to upload an additional file, they will get this response.

The candidates are, IMHO:

403 Forbidden - however, I would like to distinguish between this case and other cases where the user simply lacks the permission to perform this action.

401 Unauthorized - not a good idea, we're using this for authentication related problems.

402 Payment Required - makes kind of sense but I'm worried about using a non-standard yet reserved status code

Something even less standard like 423 Locked as its unlikely we'll use it for anything else in the future

Another option is to go with something very standard such as 403 but indicate the specifics of the error in the response body.

I'm wondering which approach you believe would (a) work best in the long run and (b) would stick more nicely to RESTful principles.


答:
I believe 403 is wrong, because 403 is for situations where you aren't getting access to the resource, and there is no way whatsoever to get access. For your customers, there is obviously a way to get access: Pay up.

401 is truly wrong, because not only are you using it for authentication, but that is what it is there for.

Since you are writing an API, I assume that someone else will have to write code that uses the API, and that person needs to read your API spec. You might go with 429 "Too many requests". It is usually intended for rate limiting (where a client can make 100 requests per day, for example), but does reasonably apply to your situation. 402 (Payment required) would also be acceptable, I think. Depends on what tools you expect people to use to use your API. 429 has the risk that a clever tool tries to send fewer requests per minute/hour/day and never succeeds.

BTW according https://www.rfc-editor.org/rfc/rfc6585 the 429 error should also contain an html message describing the nature of the problem, so there's a good chance that the user is actually told what the problem is, if you supply that information in your response.


答:
Using a hash is a good idea. Since security is not the goal in this case, choose a hash function that is fast (md5 is fine).

Unless you plan to split the hash calculation across multiple threads/processes, you don't really need to store the current hash value in the database. If your process is a single script, you will just have the current hash in memory, and will write it to the database as the old hash after you have updated the data in the new database.

Title: Best way to synchronize data between two different databases

Body:
I have to implement data synchronization between two big databases which have completely different structures. Basically, I need to grap some data about products in different tables in the first database and re-arrange them for other tables in the second database.

Creating my products on the first time is not very complicated. But I'm looking for a way to update some specific data - not all data - about each product.

Obviously, there are a few issues that make this tricky.

I'm not allowed to do anything on the source database apart select queries.

On the target database, I can do usual queries (select, update, insert, create) but I can't modify the existing structure/tables.

Target and source db have completely different structures, tables are not the same at all, therefore data really have to be rearranged - comparing tables won't work.

Target database uses a MySQL server - source may be DB2.

There are no "updated time" fields anywhere.

So the whole process needs to be done in a single Python (ideally) script.

I think about creating a hash for each product, based on the fields to update in the target database: md5( code + description + supplier + around 10 other fields). A new hash based on the same data will be created on a daily basis from the source database. I will store all hashes in a single table ( item code, current_hash, old_hash ) for performances purpose. Then compare and update the product if the new hash is different from the old one.

There are around 500 000 products so I'm a bit worried about performances.

Is it the good way to go?


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答:
I did study Latin at school, and I speak a few Latin-derived languages. I wouldn't say that Latin is "logical", not more than English. It is a natural (as opposed to constructed) language, and contains its irregularities and quirks as you would expect.

Having said that, linguistics is a fascinating subject with some connections to programming and software development. Formal grammars are connected to grammar in natural languages, and you will discover more and more links as you study.

If you are interested in "logical" human languages, have a look at "conlangs", or constructed languages. Some of them have been engineered to be "perfectly logical", so to speak. Look here.


问:
Android & OutOfMemoryError: Possible causes besides memory leak?
In my application I keep receiving crash reports where the root cause is an OutOfMemoryError.

The app is quite image heavy (I use Picasso for all the image loading) and also has a WebView component that is used to display all kinds of content from text and images to embedded videos and animated GIFs.

I used Square's LeakCanary in some places but was unable to find consistent leaks. With my understanding of Android's runtimes being quite incomplete, this leads me to my main question:

Does an OutOfMemory always need to have a leak as the root cause or is it possible/probable that one occurs for other reasons? Which other reasons would that be? The garbage collector working not fast enough? Simply using too much heap space for (e.g.) Bitmaps? Is there anything that can be done about these problems?

EDIT: To make it more clear what I need to know: I am quite certain that no single allocation I am doing is exceeding the total available heap space. It is just that occasionally I seem to get too much space used up so that some random allocation after that fails; at least the crashes are actually quite rare and not easily reproducable. Is that a reasonably certain sign of an earlier leak or is it still possible that I just have "too much going on" at once and there really is nothing the GC could have freed to make the current allocation work?END EDIT

If you think I should keep looking for memory leaks: Apart from Activitys, which LeakCanary tracks automatically what are some good places to look for leaks?

答:
Though compressed for storage, images can take up much more space internally as they are mapped into the display memory. Combine this with the wide variation in device capacities among Android devices, and you're likely to hit the memory limits of the less capable devices.

If possible, you can try to keep track of images that are not currently in the visible screen area and unload them. You would reload them as needed as they get scrolled into view (or get close to it). The WebView may or may not do this for you.


问:
Java: using final keyword only on method parameters that expect immutable objects?
I came across the interesting topic about final method parameters and that they essentially don't provide much advantages. I wondered if it would be sensible to mark only those method parameters as final, when it is advisable to pass an immutable object.

I don't know if this might mislead some people when they're reading the code, because final does not provide this immutability, and even the compiler wouldn't understand that I would like an immutable object to be passed to this method param. But it would be sth like a "human-readable" indicator (especially in APIs) that passing an immutable object is advised.

How would such a concept be evaluated by experienced java programmers?

答:
I don't think it is a good idea:

using final for a method parameter, as you noticed, does not give any immutability guarantees

I personally find that it clutters the code unnecessarily

People using your code should not have to read your code! final is not part of the method contract / its javadoc so it is not the right medium to convey information to the callers.

I would rather indicate in the javadoc the assumptions made by the method:

```<code>/**
 *  This method expects its argument to be immutable
 */
</code>```

ps: I'm not sure why you want to receive an immutable object though as it makes no difference for the code in your method (unless you spawn new threads etc.)...

Body:
I don't think it is a good idea:

using final for a method parameter, as you noticed, does not give any immutability guarantees

I personally find that it clutters the code unnecessarily

People using your code should not have to read your code! final is not part of the method contract / its javadoc so it is not the right medium to convey information to the callers.

I would rather indicate in the javadoc the assumptions made by the method:

/**
 *  This method expects its argument to be immutable
 */

ps: I'm not sure why you want to receive an immutable object though as it makes no difference for the code in your method (unless you spawn new threads etc.)...


问:
How valuable is decoupling in proprietary software?
When developing with Symfony2 PHP framework I often see reccomendations to decouple code but most of the time that is accompanied by a 'if you want to release as a third party bundle'.

Which begs the questions, if my software is proprietary should I even bother to decouple it for e.g., using interfaces and models (abstract classes) for defining domain objects. You can use an ORM and create entities which extend from models and if you want to change to an ODM you can create a Document which extends from the model. This is just an example, there are more like having a UserManager which implements a UserManagerInterface (why need this in proprietary software which is never gonna be released to the public).

Decoupling to me looks more like a way to satisfy all needs when releasing your code as open source, which can adapt to most needs.

答:
You couldn't be more wrong.

Decoupling is not for the benefit of third-party integrators who might want to take one of your components and rig it together with someone else's other component. The entire idea of reusable software objects that might be sold separately has been a gigantic disappointment, because it's simply too difficult to define clearly and umabiguously want precisely it is that a component is supposed to do.

The benefit is rather that modularized software with isolated parts is far easier to think about and work with, even when all the parts were written by yourself. This is an effect that only becomes perceptible when you program "in the large", beyond the threshold where you can actually hold all details in your head simultaneously. For that reason, there is never a shortage of beginners who think that as geniuses, they don't need structure, modules or visibility restrictions; this is part of the reason why there are so many large projects with an atrociously bad architecture.

In short, decoupling is a good idea because it helps you understand your own creation better. You should only disregard it if you really are a genius (and have no collaborators).


问:
Using sourcetree/bitbucket how can I manage multiple projects using a common codebase?
I have made a few libraries that different projects use.

When I make changes to projects, I sometimes make changes to the codebase, and I want to be able to manage this all through sourcetree.

So, for example, I have a project with global.js and project1.js.
I also have another project with global.js and project2.js.

I never want to merge project2.js with project1 and vice-versa, however, any changes I make to global.js in either project, I want to be able to merge.

As this is work for separate companies, it is important that the code is never brought across to the wrong project.

This is obviously quite a simple example, however, in reality there are many files to deal with.

For these particular projects, the changes to each individual project is stored in subfolders to keep the project specific code separate to the global code.

eg:
codebase/includes/global.js etc..

codebase/modules/project1
or
codebase/modules/project2

What is the recommended way of managing this using sourcetree/bitbucket?

答: The usual way is using whatever is common for distributing libraries in the eco system for your language. For C# publish a nuget package. For Java look into how maven downloads packages. For ruby publish a ruby gem. For python distribute a module. For perl look into cpan etc. In your code just refer to whatever you publish and your code is essentially on par with any third party tools you are using.</p>


问:
Storing exception information as a member variable for query later, bad practice?
I looking at the best way to handle exceptions, the answer to this question may be to handle the exception in a different place or to not handle to exception at all but to control the flow of the code. Please let me know if this is the case.

Lets say we have a class NetworkConnection. This class has a Connect method that looks like:

bool Connect(string ipAddress, int port)
{
   try
   {
       // do connection, when successful
       return true;
   }
   catch (HostNotFoundException ex)
   {
       return false;
   }
   catch (...)
   {
       ...
   }
}
```

If another object using this method wants to know what exception occurred it cannot find out. There are three ways of dealing with this that I can think of:

Return an error code

Store a variable on the NetworkConnection object that contains some error info, perhaps a string saying 'Host not found', this can then be queried by another object later on.

Catch the exception higher up in the code base.

I want to choose the second method but I sense that this would be a bad idea. What is the best decision here, why (potentially) is my chosen bad?

答:
Its a reasonably common practice - C programs (and other systems, eg errno) often to store the last error in a location so you can pick the details out if a function returned an error code. There's no reason why you can't do the same.

However, if you do this you have to take a few things into consideration. Threads are very important, each error info must be stored per thread and you cannot get anything but the very-last-error, which could be tricky if you are expecting a different area of code to read it - a different call may change it between the time you write it and you want to read it. As a result, its not recommended in general.

What you might want to do is log all errors and let the other routine read off the list, this may work for auditing or errors that are specifically designed for the user to view.

IMHO exceptions are for exceptional circumstances. For expected errors, a return code is superior. Using exceptions for code-flow is bad practice. Return an error code and let the caller decide what to do with that. IF you must use exceptions, handle it further up the call stack.


问:
When to use single-line if statements?
When reviewing code, I prefer to read if statements that explicitly demonstrate that a fork in code execution may occur:

```<code>if ( isFoo(baz) ) {
    runBar();
}
</code>```

When scanning hundreds of lines of the nonindented version, it is not obvious that a conditional may or may not occur:

```<code>boom += 1;
baz = getBaz(boom);
if (isFoo(baz)) runBar();
boing = boom + baz;
</code>```

So when is it considered all right to single-line if statements? I'm willing to put up with it if the conditional is on a die(), return, or exception, because in those cases at least the current method ends.

```<code>if (isFoo(baz)) die("No more foo!");
</code>```

Are there any other "good" uses for single-line if statements? How strictly should the practice be avoided? Note that I am explicitly asking about the lack of an indented line to indicate that a condition may or may not occur, I am not asking about the use of braces. Although I would appreciate all opinions in the comments, answers should address objective reasoning, such as maintainability or extensibility of code.

This is not a dupe of Single statement if block - braces or no because this question does not ask about braces. This is not a dupe of Single Line Statements & Good Practices because that question does not address the crux of this question: the ability to determine that some lines of code may or may not be run, thus leading to divergent code paths.

答:
The only time to use a single-line if statement is when you have a lot of them and you can format your code to make it very clear what is happening. Anything else is not clear and will lead to errors.

eg.

```<code>if (x) do_stuff();
</code>```

is terrible. When mixed in with other code, it does not clearly show the conditional statement, and some people will confuse the following line as a badly-indented conditional. This applies to all statements, especially if they are die(), return or throw. It has nothing to do with the running of the code, its all about the readability.

```<code>if (a) do_a();
if (b) do_b();
if (c) do_c();
</code>```

this is much better than putting the conditionals on the next line as its clearer what is intended, there is no scope for confusion.

Title: When to use single-line if statements?

Body:
The only time to use a single-line if statement is when you have a lot of them and you can format your code to make it very clear what is happening. Anything else is not clear and will lead to errors.

eg.

if (x) do_stuff();

is terrible. When mixed in with other code, it does not clearly show the conditional statement, and some people will confuse the following line as a badly-indented conditional. This applies to all statements, especially if they are die(), return or throw. It has nothing to do with the running of the code, its all about the readability.

if (a) do_a();
if (b) do_b();
if (c) do_c();

this is much better than putting the conditionals on the next line as its clearer what is intended, there is no scope for confusion.


答:
Latin is a more "regular" language than English, in the sense that the rules are much more strictly followed. Does that make it any more "logical" in the sense of mathematical or programming logic? Not sure.

But studying Latin definitely improved my understanding of English, my native language. And learning any other language inevitably improves your communication ability generally. I think that translates to writing computer programs as well.

Title: Does knowing Latin or other logical languages contribute to being a better programmer?

Body:
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?


问:
Is testable code better code?
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.

答:
Yes, it is good practice. The reason is that testability is not for the sake of tests. It is for the sake of clarity and understandability that it brings with it.

Nobody cares about the tests themselves. It is a sad fact of life that we need large regression test suites because we're not brilliant enough to write perfect code without constantly checking our footing. If we could, the concept of tests would be unknown, and all of this wouldn't be an issue. I certainly wish I could. But experience has shown that almost all of us can't, therefore tests covering our code are a good thing even if they take away time from writing business code.

How does having tests improve our business code independently of the test themselves? By forcing us to segment our functionality into units that are easily demonstrated to be correct. These units are also easier to get right than the ones we'd otherwise be tempted to write.

Your time example is a good point. As long as you only have a function returning the current time you might think that there's no point in having it programmable. How hard can it be to get this right? But inevitably your program will use this function in other code, and you definitely want to test that code under different conditions, including at different times. Therefore it's a good idea to be able to manipulate the time that your function returns - not because you mistrust your one-line currentMillis() call, but because you need to verify the callers of that call under controlled circumstances. So you see, having code testable is useful even if on its own, it doesn't seem to merit that much attention.

Title: Is testable code better code?


答:
I always prefer the version with braces.

If I don't always use the braces, then I may forget to put them when there is more than one statement in the block.

IDEs used by other team members can reformat the code automatically to move the statement to the new line, thus making it much more error prone in the future.

Merging the code across the branches is more error prone if the if statement is a conflicting spot. The probability for error is even higher if the person doing the merge is not completely familiar with the merged changes.

A statement not-belonging to the block may be included in it later by mistake (I add new statements to the block, so I need to add braces, but because of indentation or similar visual effects I also include a statement that should be left out of the block).

Title: When to use single-line if statements?

Body:
When reviewing code, I prefer to read if statements that explicitly demonstrate that a fork in code execution may occur:

```<code>if ( isFoo(baz) ) {
    runBar();
}
</code>```

When scanning hundreds of lines of the nonindented version, it is not obvious that a conditional may or may not occur:

```<code>boom += 1;
baz = getBaz(boom);
if (isFoo(baz)) runBar();
boing = boom + baz;
</code>```

So when is it considered all right to single-line if statements? I'm willing to put up with it if the conditional is on a die(), return, or exception, because in those cases at least the current method ends.

```<code>if (isFoo(baz)) die("No more foo!");
</code>```

Are there any other "good" uses for single-line if statements? How strictly should the practice be avoided? Note that I am explicitly asking about the lack of an indented line to indicate that a condition may or may not occur, I am not asking about the use of braces. Although I would appreciate all opinions in the comments, answers should address objective reasoning, such as maintainability or extensibility of code.

This is not a dupe of Single statement if block - braces or no because this question does not ask about braces. This is not a dupe of Single Line Statements & Good Practices because that question does not address the crux of this question: the ability to determine that some lines of code may or may not be run, thus leading to divergent code paths.


问:
What are the advantages of build scripts?
For most of my programming career, I've used the "build/compile/run" command in whatever IDE I'm working with to produce a runnable program. This is one button, pretty easy. As I learn more about different languages and frameworks, though, I see more and more talk of "build scripts" (ANT, Maven, Gradle, etc.) to get a project running. My understanding of these is that they are instructions to the compiler/linker/magical-program-maker that specify configuration details - minutiae.

I remember writing makefiles back in school, but I didn't see any special advantage then (we only used them when writing in a Unix terminal, where an IDE with it's handy "build" button wasn't present). Beyond that, I've seen other questions on here that discuss how build scripts can do more than just create your program - they can run unit tests as well as secure resources regardless of the host machine.

I can't shake the feeling that build scripts are important to understand as a developer, but I'd like a meaningful explanation; why should I use/write build scripts?

Responsibilities of Build Script and Build Server discusses the role it plays within a broader scope. I'm looking for specific advantages offered by a build script versus an IDE's "build/run" command or similarly simple methods.

答:
Build script advantages:

changes look like code (for example, in a git diff command), not like different checked options in a dialog

creating more output than a simple build

In some of my previous projects, I've used the build scripts to:

generate the project documentation (doxygen-based)

build

run unit tests

generate unit test coverage reports

pack binaries into a release archive

generate internal release notes (based on "git log" messages)

automated testing


答:
In regard to the common definition of unit tests, I'd say no. I've seen simple code made convoluted because of the need to twist it to suit the testing framework (eg. interfaces and IoC everywhere making things difficult to follow through layers of interface calls and data that should be obvious passed in by magic). Given the choice between code that is easy to understand or code that is easy to unit test, I go with the maintainable code every time.

This doesn't mean not to test, but to fit the tools to suit you, not the other way round. There are other ways to test (but difficult-to-understand code is always bad code). For example, you can create unit tests that are less granular (eg. Martin Fowler's attitude that a unit is generally a class, not a method), or you can hit your program with automated integration tests instead. Such may not be as pretty as your testing framework lights up with green ticks, but we're after tested code, not the gamification of the process, right?

You can make your code easy to maintain and still be good for unit tests by defining good interfaces between them and then writing tests that exercise the public interface of the component; or you could get a better test framework (one that replaces functions at runtime to mock them, rather than requiring the code to be compiled with mocks in place). A better unit test framework lets you replace the system GetCurrentTime() functionality with your own, at runtime, so you don't need to introduce artificial wrappers to this just to suit the test tool.

Title: Is testable code better code?

Body:
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.


答:
Is writing testable code still good practice even in the absence of tests?

First things first, an absence of tests is a way bigger issue than your code being testable or not. Not having unit tests means you're not done with your code/feature.

That out of the way, I wouldn't say that it's important to write testable code - it's important to write flexible code. Inflexible code is hard to test, so there's a lot of overlap there in approach and what people call it.

So to me, there is always a set of priorities in writing code:

Make it work - if the code doesn't do what it needs to do, it is worthless.

Make it maintainable - if the code isn't maintainable, it will quickly stop working.

Make it flexible - if the code isn't flexible, it will stop working when business inevitably comes by and asks if the code can do XYZ.

Make it fast - beyond a base acceptable level, performance is just gravy.

Unit tests help code maintainability, but only to a point. If you make the code less readable, or more fragile to make the unit tests work, that gets counter productive. "Testable code" is generally flexible code, so that is good, but not as important as functionality or maintainability. For something like the current time, making that flexible is good but it harms maintainability by making the code harder to use right and more complex. Since maintainability is more important, I will usually err towards the simpler approach even if it is less testable.

Title: Is testable code better code?


答:
It may seem silly to say it this way, but if you want to be able to test your code, then yes, writing testable code is better. You ask:

At some point the value needs to be initialized, and why not closest
  to consumption?

Precisely because, in the example you are referring to, it makes that code untestable. Unless you only run a subset of your tests at different times of the day. Or you reset the system clock. Or some other workaround. All of which are worse than simply making your code flexible.

In addition to being inflexible, that small method in question has two responsibilities: (1) getting the system time and then (2) returning some value based on it.

```<code>public static string GetTimeOfDay()
{
    DateTime time = DateTime.Now;
    if (time.Hour >= 0 && time.Hour < 6)
    {
        return "Night";
    }
    if (time.Hour >= 6 && time.Hour < 12)
    {
        return "Morning";
    }
    if (time.Hour >= 12 && time.Hour < 18)
    {
        return "Afternoon";
    }
    return "Evening";
}
</code>```

It makes sense to break down the responsibilities further, so that the part out of your control (DateTime.Now) has the least impact on the rest of your code. Doing so will make the code above simpler, with the side effect of being systematically testable.

Title: Is testable code better code?

Body:
It may seem silly to say it this way, but if you want to be able to test your code, then yes, writing testable code is better. You ask:

At some point the value needs to be initialized, and why not closest
  to consumption?

Precisely because, in the example you are referring to, it makes that code untestable. Unless you only run a subset of your tests at different times of the day. Or you reset the system clock. Or some other workaround. All of which are worse than simply making your code flexible.

In addition to being inflexible, that small method in question has two responsibilities: (1) getting the system time and then (2) returning some value based on it.

public static string GetTimeOfDay()
{
    DateTime time = DateTime.Now;
    if (time.Hour >= 0 && time.Hour < 6)
    {
        return "Night";
    }
    if (time.Hour >= 6 && time.Hour < 12)
    {
        return "Morning";
    }
    if (time.Hour >= 12 && time.Hour < 18)
    {
        return "Afternoon";
    }
    return "Evening";
}

It makes sense to break down the responsibilities further, so that the part out of your control (DateTime.Now) has the least impact on the rest of your code. Doing so will make the code above simpler, with the side effect of being systematically testable.


答:
It's possible that not every characteristic which contributes to testability is desirable outside the context of testability - I have trouble coming up with a non-test-related justification for the time parameter you cite, for instance - but broadly speaking the characteristics which contribute to testability also contribute to good code regardless of testability.

Broadly speaking, testable code is malleable code.  It's in small, discrete, cohesive, chunks, so individual bits can be called for reuse.  It's well-organized and well-named (to be able to test some functionality you give more attention to naming; if you weren't writing tests the name for a single-use function would matter less).  It tends to be more parametric (like your time example), so open to use from other contexts than the original intended purpose.  It's DRY, so less cluttered and easier to comprehend.

Yes.  It's good practice to write testable code, even irrespective of testing.

Title: Is testable code better code?


答:
A quality of well-written code is that it is robust to change. That is, when a requirements change comes along, the change in the code should be proportional. This is an ideal (and not always achieved), but writing testable code helps get us closer to this goal.

Why does it help get us closer? In production, our code operates within the production environment, including integrating and interacting with all of our other code. In unit tests, we sweep away much of this environment. Our code now is being robust to change because tests are a change. We are using the units in different ways, with different inputs (mocks, bad inputs that might never actually get passed in, etc) than we would use them in production.

This prepares our code for the day when change happens in our system. Let's say our time calculation needs to take a different time based on a timezone. Now we have the ability to pass in that time and not have to make any changes to the code. When we don't want to pass in a time and want to use the current time, we could just use a default argument. Our code is robust to change because it is testable.

Title: Is testable code better code?


答:
At some point the value needs to be initialized, and why not closest to consumption?

Because you may need to reuse that code, with a different value than the one generated internally. The ability to insert the value you are going to use as a parameter, ensures that you can generate those values based on any time you like, not just "now" (with "now" meaning when you call the code).

Making code testable in effect means making code that can (from the start) be used in two different scenarios (production and test).

Basically, while you can argue there is no incentive to make the code testable in the absence of tests, there is great advantage in writing reusable code, and the two are synonyms.

Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed.

You could also argue that the purpose of this method is to return some value based on a time value, and you need it to generate that based on "now". One of them is more flexible, and if you get used to choosing that variant, in time, your rate of code reuse will go up.

Title: Is testable code better code?


答:
If you start taking the linguistics side of computer programming too seriously you'll find yourself wanting to write a better language.
Which will require you to write a parser.
Which will then enable you to lay down language fundamentals.
Which enables you to write higher programming constructs.
Which will point out deficiencies in your language.
Which will lead to you re-writing your parser.
Which will eventually drive you insane in a quest to find a perfect expressive pattern to encapsulate an idea that would've just taken 15 min to write in VBA.

In other words, don't look that deeply into it.


答:
It certainly has a cost, but some developers are so accustomed to paying it that they've forgotten the cost is there.  For your example, you now have two units instead of one, you've required the calling code to initialize and manage an additional dependency, and while GetTimeOfDay is more testable, you are right back in the same boat testing your new IDateTimeProvider.  It's just that if you have good tests, the benefits usually outweigh the costs.

Also, to a certain degree, writing testable code sort of encourages you to architect your code in a more maintainable way.  The new dependency management code is annoying, so you'll want to group all your time-dependent functions together, if at all possible.  That can help to mitigate and fix bugs like, for example, when you load a page right on a time boundary, having some elements rendered using the before time and some using the after time.  It can also speed up your program by avoiding repeated system calls to get the current time.

Of course, those architectural improvements are highly dependent on someone noticing the opportunities and implementing them.  One of the biggest dangers of focusing so closely on units is losing sight of the bigger picture.

Many unit test frameworks let you monkey patch a mock object in at runtime, which lets you get the benefits of testability without all the mess.  I've even seen it done in C++.  Look into that ability in situations where it looks like the testability cost isn't worth it.

Title: Is testable code better code?