答:
I would suggest you encapsulate that logic in the place where you can actually delete the milestone since the removal of its ID from the tickets is an implementation detail of the business logic at the point of deletion. The important thing is to do it in a single obvious place in a transaction so that either everything happens or nothing happend.

If you are using the repository pattern, you could do something along these lines:

```<code>void Delete(int milestoneId)
{
    db.BeginTransaction();
    db.Execute("UPDATE Tickets SET MilestoneID = null WHERE MilestoneID = @p0", milestoneId);
    db.Execute("DELETE FROM Milestones WHERE MilestoneID = @p0", milestoneId);
    db.Commit();
}
</code>```

It's subject to personal preference a little here as you could argue that the MilestoneRepository shouldn't know about Tickets but depending on how many other requirements you have along these lines (e.g. if there aren't many) it might be acceptable for now. The other option is to create a service which has this knowledge like this:

```<code>class MilestoneRepository
{
    void Delete(int milestoneId)
    {
        db.Execute("DELETE FROM Milestones WHERE MilestoneID = @p0", milestoneId);
    }
}

class TicketRepository
{
    void DetachAllFromMilestone(int milestoneId)
    {
        db.Execute("UPDATE Tickets SET MilestoneID = null WHERE MilestoneID = @p0", milestoneId);
    }
}

class MilestoneService
{
    void Delete(Milestone milestone)
    {
        unitOfWork.Begin(); // start transaction
        ticketRepository.DetachAllFromMilestone(milestone.Id);
        milestoneRepository.Delete(milestone.Id);
        unitOfWork.Complete(); // commit transaction
    }
}
</code>```

Title: How do I design a DAL when I have to deal with relationships?

Body:
Say I'm developing a bug tracker, where a ticket belongs to at most one milestone, and a milestone can have many tickets. When a milestone is deleted (from the database), all tickets associated with that milestone must have their relationship unset (i.e. set to null). This is a simple relationship.

The classes are fairly simple, and map directly to a database:

```<code>public class Ticket {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
    public ObjectId MilestoneId { get; set; }
}

public class Milestone {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}
</code>```

Now comes the tricky part: where and how do I reset the MilestoneId fields? One possible solution is to write a data access layer by creating one giant class with all data accessing methods for all kinds of objects, in this case tickets and milestones. Another possible solution is to write several classes (e.g. TicketProvider and MilestoneProvider), one for each kind of object, that provide data accessing methods such as Find, Save and Destroy.

The latter appeals more to me since I don't like monsterous classes, but there is one caveat: the method that deletes milestones has to reset the MilestoneIds of all associated tickets to null. This means that MilestoneProvider, which is responsible for manipulating milestones, suddenly deals with tickets!

How are relationships commonly dealt with in data access layers, and how can I prevent violation of SRP? Should I put the entire DAL in one class, or should I separate it and if so, how can I best do that?

Body:
I would suggest you encapsulate that logic in the place where you can actually delete the milestone since the removal of its ID from the tickets is an implementation detail of the business logic at the point of deletion. The important thing is to do it in a single obvious place in a transaction so that either everything happens or nothing happend.

If you are using the repository pattern, you could do something along these lines:

void Delete(int milestoneId)
{
    db.BeginTransaction();
    db.Execute("UPDATE Tickets SET MilestoneID = null WHERE MilestoneID = @p0", milestoneId);
    db.Execute("DELETE FROM Milestones WHERE MilestoneID = @p0", milestoneId);
    db.Commit();
}

It's subject to personal preference a little here as you could argue that the MilestoneRepository shouldn't know about Tickets but depending on how many other requirements you have along these lines (e.g. if there aren't many) it might be acceptable for now. The other option is to create a service which has this knowledge like this:

class MilestoneRepository
{
    void Delete(int milestoneId)
    {
        db.Execute("DELETE FROM Milestones WHERE MilestoneID = @p0", milestoneId);
    }
}

class TicketRepository
{
    void DetachAllFromMilestone(int milestoneId)
    {
        db.Execute("UPDATE Tickets SET MilestoneID = null WHERE MilestoneID = @p0", milestoneId);
    }
}

class MilestoneService
{
    void Delete(Milestone milestone)
    {
        unitOfWork.Begin(); // start transaction
        ticketRepository.DetachAllFromMilestone(milestone.Id);
        milestoneRepository.Delete(milestone.Id);
        unitOfWork.Complete(); // commit transaction
    }
}


问:
REST efficiency on count and sum methods
For example, if I have a Customer Transactions Table and I create a REST for it. The fields are: date, description, and total_amount.

I am trying to figure out which one is much more efficient when you get the sum and the count of the transactions:

You create a REST for /transactons URI and it lists down all the transactions. Then, you sum all transactions using javascript and you count all transactions using javascript.

You create a REST for /transactions/count and /transactions/sum URI and lists down count and sum for all transactions. Then, get the count and sum using javascript.

I'm wondering which one is a better way.

答:
It depends on how many transactions you expect. In general, it seems that if you only want the sum and count then transferring all the details is inefficient.

However, if the number of transactions is very small then the overhead of multiple requests might be more inefficient.

Personally, I like the second option, but I would add a third REST endpoint /transactions/aggregate that returns some or all of the aggregate data.

ContentLicense: CC BY-SA 3.0


问:
When did the standard for packaging Linux source code become .tar.gz?
When browsing open-source projects that are primarily developed for Linux systems and downloading the latest packages, the source code is always stored in a .tar.gz or .tar.bz2 file.

Is there any reason for using .tar.gz or .tar.bz2 rather than something like .zip or .rar or some other compression algorithm (or even leaving it uncompressed if the project is small enough)?

答:
To answer the question in the heading: tar.gz/tar.bz2 became the standard for distributing Linux source code a very very very long time ago, as in well over 2 decades, and probably a couple more. Significantly before Linux even came into existence.

In fact, tar stands for (t)ape (ar)chive. Think reel hard, and you'll get an idea how old it is. ba-dum-bump.

Before people had CD burners, distros of software were put out on 1.44Mb floppy disks. The compressed tar file was chopped into floppy-sized pieces by the split command, and these pieces were called tarballs. You'd join them back together with cat and extract the archive.

To answer the other question of why not Zip or Rar, that's an easy one. The tar archiver comes from Unix, while the other two come from MS-DOS/Windows. Tar handles unix file metadata (permissions, times, etc), while zip and rar did not until very recently (they stored MS-DOS file data). In fact, zip took a while before it started storing NTFS metadata (alternate streams, security descriptor, etc) properly.

Many of the compression algorithms in PKZip are proprietary to the original maker, and the final one added to the Dos/Windows versions was Deflate (RFC 1951) which performed a little better than Implode, the proprietary algo in there that produced the best general compression. Gzip uses the Deflate algorithm.

The RAR compression algorithm is proprietary, but there is a gratis open source implementation of the decompressor. Official releases of RAR and WinRAR from RARlab are not gratis.

Gzip uses the deflate algorithm, and so is no worse than PKZip. Bzip2 gets slightly better compression ratios.

TL;DR version:

tar.gz and tar.bz2 are from Unix, so Unix people use them. Zip and Rar are from the DOS/Windows world, so DOS/Windows people use them. tar has been the standard for bundling archives of stuff in *nix for several decades.


问:
what is the best way to ensure accountability in code checkins?
Note:  after writing this I realize that this question is perhaps philosophical, but I'm interested in how the industry handles this scenario regardless.

I have recently been working with a code base that is not yet as testable as it should be.  I've seen some junior developers check in code that breaks use cases, which is usually identified by another developer a few days after the check-in.

Assuming that we can't achieve code coverage yet, are there technical solutions for holding developers accountable for bad check-ins in addition to a non-technical approach; discussing the commit and having the dev address the issue in a new commit.

答: If you use git for version control check out gerrit. Sure it can be a pain in the ass, but it does require code reviews to take place before a commit is merged into the repository.</p>


问:
How do open source projects maintain quality?
How do open source projects maintain quality?
What keeps the projects from people with relatively little programming experience checking in poor quality codes?</p>

答:
What keeps the projects from people with relatively little programming experience checking in poor quality codes?

Usually, not everyone have the rights to change the source code. Most often there is only a small group of trusted developers that have rights to change the source code. If someone else wants to make changes, they can submit patches, but these are checked and added by the developers with commit access.

Some projects allow other developers to join the trusted group, if they submit several patches of sufficient quality.

ContentLicense: CC BY-SA 2.5


问:
How do I design a DAL when I have to deal with relationships?
Say I'm developing a bug tracker, where a ticket belongs to at most one milestone, and a milestone can have many tickets. When a milestone is deleted (from the database), all tickets associated with that milestone must have their relationship unset (i.e. set to null). This is a simple relationship.

The classes are fairly simple, and map directly to a database:

```<code>public class Ticket {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
    public ObjectId MilestoneId { get; set; }
}

public class Milestone {
    public ObjectId Id { get; set; }
    public string Title { get; set; }
}
</code>```

Now comes the tricky part: where and how do I reset the MilestoneId fields? One possible solution is to write a data access layer by creating one giant class with all data accessing methods for all kinds of objects, in this case tickets and milestones. Another possible solution is to write several classes (e.g. TicketProvider and MilestoneProvider), one for each kind of object, that provide data accessing methods such as Find, Save and Destroy.

The latter appeals more to me since I don't like monsterous classes, but there is one caveat: the method that deletes milestones has to reset the MilestoneIds of all associated tickets to null. This means that MilestoneProvider, which is responsible for manipulating milestones, suddenly deals with tickets!

How are relationships commonly dealt with in data access layers, and how can I prevent violation of SRP? Should I put the entire DAL in one class, or should I separate it and if so, how can I best do that?

答:
As an alternative to doing it in middle-tier business logic code, I offer up a Microsoft SQL Server trigger:</p>

```<code>CREATE TRIGGER dbo.DeleteMilestone
  ON dbo.Milestone
  INSTEAD OF DELETE
AS
  BEGIN TRANSACTION

  UPDATE t
  SET t.MilestoneId = NULL
  FROM dbo.Ticket t
  INNER JOIN DELETED d ON t.MilestoneId = d.Id;

  DELETE m
  FROM dbo.Milestone m
  INNER JOIN DELETED d ON m.Id = d.Id;

  COMMIT TRANSACTION
GO
</code>```

Body:
As an alternative to doing it in middle-tier business logic code, I offer up a Microsoft SQL Server trigger:

CREATE TRIGGER dbo.DeleteMilestone
  ON dbo.Milestone
  INSTEAD OF DELETE
AS
  BEGIN TRANSACTION

  UPDATE t
  SET t.MilestoneId = NULL
  FROM dbo.Ticket t
  INNER JOIN DELETED d ON t.MilestoneId = d.Id;

  DELETE m
  FROM dbo.Milestone m
  INNER JOIN DELETED d ON m.Id = d.Id;

  COMMIT TRANSACTION
GO


问:
How do I prevent unknowningly duplicating code?
I work on a rather large code base. Hundreds of classes, tons of different files, lots of functionality, takes more than 15 minutes to pull down a fresh copy, etc.

A big problem with such a large code base is that it has quite a few utility methods and such that do the same thing, or has code that doesn't use these utility methods when it could. And also the utility methods aren't just all in one class (because it'd be a huge jumbled mess).

I'm rather new to the code base, but the team lead who's been working on it for years appears to have the same problem. It leads to a lot of code and work duplication, and as such, when something breaks, it's usually broken in 4 copies of basically the same code

How can we curb this pattern? As with most large projects, not all code is documented(though some is) and not all code is... well, clean. But basically, it'd be really nice if we could work on improving the quality in this respect so that in the future we had less code duplication, and things like utility functions were easier to discover.

Also, the utility functions are usually either in some static helper class, in some non-static helper class that works on a single object, or is a static method on the class which it mainly "helps" with.

I had one experiment in adding utility functions as Extension methods(I didn't need any internals of the class, and it definitely was only required in very specific scenarios). This had the effect of preventing cluttering up the primary class and such, but it's not really anymore discoverable unless you already know about it

答:
Don't forget that the code duplication is not always harmful. Imagine: now you have some task  to be solved in absolutely different modules of your project. Just now it is the same task.

There could be three reasons for it:

Some theme around this task is the same for both modules. In this case the code duplication is bad and should be liquidated. It would be clever to create a class or a module to support this theme and use its methods in both modules.

The task is theoretical in terms of your project. For example, it is from physics or maths etc. The task exists independently on your project. In this case the code duplication is bad and should be liquidated, too. I'd create a special class for such functions. And use a such function in any module where you need it.

But in other cases the coincidence of tasks is a temporary coincidence and nothing more.
It would be dangerous to believe that these tasks will remain the same during changes of the project due to refactoring and even debugging. In this case it would be better to create two same functions/pieces of code in different places. And future changes in one of them won't touch the other one.

And this 3rd case happens very often. If you duplicate "unknowlingly", mostly it is for this very reason - it is not a real duplication!

So, try to keep it clean when it is really necessary and don't be afraid of duplication if it is not the must.


问:
What is the reason behind methods with return values and methods with void?
I want to uderstand why there is a method in C# that could reurn a value, for example:

```<code>public int Accelerate()
{
   Speed++;
   return Speed;
}
</code>```

and a method that does not reurn a value (void)?

What is the difference in the following example of the above one:

```<code>public void Accelerate()
{
  Speed++;
  Console.WriteLine(Speed);
}
</code>```

I see that last one will save us a time rather than defining a variable to hold this field in when creating a new object! I'm beginner, so could anyone explain?

答:
The second one only works within a console based app. It assumes you want to print the speed in a console screen.

The first one will work on a console, or as part os a web app, or as part of a GUI based desktop app, or mobile app.

The first one is therefore more useful as part of a modular system.

The second one is doing a calculation and also printing to screen, mixing the business logic with the presentation, which is bad.

That said, first method shouldn't even return the value. A separate getSpeed() method should exist to return that value. Accelerate should only increment the speed.

Also the variable should be named speed in lowercase and the method whould be called accelerate() also in lowercase.


答:
because in most applications you want to do something with the new speed, like finding the relative speed between 2 objects, the your code there is no way to get the new speed (unless you have a separate method for that

also if you wrote everything out to the console you'd have a ton of spam on it, take minecraft it runs at 20 "ticks" a second with up to a hundred different moving entities, having 2000 messages of speed or position per second in the log is utterly useless and writing this out will lag the game

for another point it is not the responsibility of the accelerate method to write things out to the console

Title: What is the reason behind methods with return values and methods with void?

Body:
I want to uderstand why there is a method in C# that could reurn a value, for example:

```<code>public int Accelerate()
{
   Speed++;
   return Speed;
}
</code>```

and a method that does not reurn a value (void)?

What is the difference in the following example of the above one:

```<code>public void Accelerate()
{
  Speed++;
  Console.WriteLine(Speed);
}
</code>```

I see that last one will save us a time rather than defining a variable to hold this field in when creating a new object! I'm beginner, so could anyone explain?


问:
Should database queries be abstracted out of the page itself?
When writing page generation in PHP, I often find myself writing a set of files littered with database queries. For example, I might have a query to fetch some data about a post directly from the database to display on a page, like this:

```<code>$statement = $db->prepare('SELECT * FROM posts WHERE id=:id');
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$post = $statement->fetch(PDO::FETCH_ASSOC);
$content = $post['content']
// do something with the content
</code>```

These quick, one-off queries are usually small, but I sometimes end up with large portions of database interaction code which begins to look pretty messy.

In some cases, I've solved this problem by creating a simple library of functions to handle my post-related db queries, shortening that block of code to a simple:

```<code>$content = post_get_content($id);
</code>```

And that's great. Or at least it is until I need to do something else. Maybe I need to get the five most recent posts to display in a list. Well, I could always add another function:

```<code>$recent_posts = post_get_recent(5);
foreach ($recent_posts as $post) { ... }
</code>```

But that ends up using a SELECT * query, which I usually really don't need anyway, but is often too complicated to reasonably abstract. I eventually end up with either a massive library of database interaction functions for every single use case, or a series of messy queries inside every page's code. And even once I've built these libraries, I'll find myself needing to do one tiny join that I hadn't used before, and I suddenly need to write another highly-specialized function to do the job.

Sure, I could use the functions for general use cases and queries for specific interactions, but as soon as I start writing raw queries I begin to slip back into direct access for everything. Either that, or I'll get lazy and will start doing things in PHP loops that should really be done directly in the MySQL queries, anyway.

I'd like to ask those more experienced with writing internet applications: is the maintainability boost worth the extra lines of code and possible inefficiencies that the abstractions may introduce? Or is simply using direct query strings an acceptable method for handling database interactions?

答:
I assume that when you say "the page itself" you mean the PHP source file that dynamically generates HTML.

Do not query the database and generate HTML in the same source file.

The source file where you query the database is not a "page", even though it's a PHP source file.

In the PHP source file where you dynamically create the HTML you just make calls to the functions that are defined in the PHP source file where the database is accessed.


问:
Is it ever ok to have an empty catch statement?
I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>

答:
In some cases, the exception is not at all exceptional; in fact, it is expected. Consider this example:

```<code>    /* Check if the process is still alive; exitValue() throws an exception if it is */
    try {
        p.exitValue();
        processPool.remove(p);
    }
    catch (IllegalThreadStateException e) { /* expected behaviour */ }
</code>```

Since there is no isAlive() method in java.lang.Process(), about the only way to check if it is still alive is to call exitValue(), which throws an IllegalThreadStateException if the process is still running.

Body:
In some cases, the exception is not at all exceptional; in fact, it is expected. Consider this example:

    /* Check if the process is still alive; exitValue() throws an exception if it is */
    try {
        p.exitValue();
        processPool.remove(p);
    }
    catch (IllegalThreadStateException e) { /* expected behaviour */ }

Since there is no isAlive() method in java.lang.Process(), about the only way to check if it is still alive is to call exitValue(), which throws an IllegalThreadStateException if the process is still running.


答:
I second code reviews.  Some tools let you do reviews before the code is committed like Github pull requests.  Others let you see who touched each line like SVN blame.

Personally, I'd rather my team members commit code to the trunk frequently even if it isn't perfect.  It increases the chances someone else will notice an issue and allows for the benefits of continuous integration.

We do formal code reviews at the end of a task.  I also do "random" code reviews as people work and commit.  The random is in quotes, because I review more heavily at the beginning to train people well how to test.  I'll also offer to pair to test so developers gain the skills.  The random is also in quotes because people who write worse code/tests get chosen more often for the random reviews.  I keep the random reviews anonymous - management never hears about them - they are a purely team practice.

Title: what is the best way to ensure accountability in code checkins?

Body:
Note:  after writing this I realize that this question is perhaps philosophical, but I'm interested in how the industry handles this scenario regardless.

I have recently been working with a code base that is not yet as testable as it should be.  I've seen some junior developers check in code that breaks use cases, which is usually identified by another developer a few days after the check-in.

Assuming that we can't achieve code coverage yet, are there technical solutions for holding developers accountable for bad check-ins in addition to a non-technical approach; discussing the commit and having the dev address the issue in a new commit.


答:
I think your team needs to attend an agile scrum course and make a pact to follow the methodology.

When developers check-in small code changes assigned to small tasks it reduces the chance of developers going off the rails and checking-in conflicting code. This increases continuous integration.

"I've seen some junior developers check in code that breaks use cases,
  which is usually identified by another developer a few days after the
  check-in."

Even in a perfect world this still happens. If you find its happening frequently and/or after several days of development then you have a problem.

I think you'll find the team will work together more effectively with a planned iteration. I suggest you try out a 2 week sprint. Start the sprint with an in-depth scrum meeting. Go through the backlog of Bugs and Work Items, accepting the top priorities and writing them down on post-it notes with units/time estimates using planning poker cards.

Line up a scrum dashboard or white board and ensure people only work on one thing at a time. Once they have finished the task they need to write a unit test for it. Once they write a working unit test they will need to get a Code Review. Constructive code reviews is one of the best techniques to prevent developers accidentally checking-in code conflicts.

After the Code Reviewer has signed off, the developer does the Check-In Dance:

Let the rest of the team know a change is coming if it’s a significant update.

Get the latest code from source control.

Do a merge on any conflicts.

Run the build locally and fix any problems found.

Run the Unit Tests locally and fix any problems found.

Commit the changes to source control.

Stop coding until the build passes.

If the build breaks, drop everything else and fix the build.

Team Foundation Server (TFS) faciliates all this stuff out-of-the-box.

You should fix up the tests before moving forward. But just because 80% of code is unit tested that doesn't mean its bug proof. Developers have to be active in testing their code sociability. This code integration is much easier to achieve using non-waterfall methodologies.


答:
The pattern I use for most middle-scale projects is the following one:

All the SQL queries are put apart from the server-side code, in a separate location.

Working with C#, it means using partial classes, i.e. putting the queries in a separate file, given that those queries will be accessible from a single class (see the code below).

Those SQL queries are constants. This is important, since it prevents the temptation of building SQL queries on the fly (thus increasing the risk of SQL injection and at the same time making it more difficult to review the queries later).

Current approach in C#

Example:

```<code>// Demo.cs
public partial class Demo : DataRepository
{
    public IEnumerable<Stuff> LoadStuff(int categoryId)
    {
        return this
            .Query(Queries.LoadStuff)
            .With(new { CategoryId = categoryId })
            .ReadRows<Stuff>();
    }

    // Other methods go here.
}

public partial class Demo
{
    private static class Queries
    {
        public const string LoadStuff = @"
select top 100 [StuffId], [SomeText]
    from [Schema].[Table]
    where [CategoryId] = @CategoryId
    order by [CreationUtcTime]";

        // Other queries go here.
    }
}
</code>```

This approach has a benefit of having the queries are in a separate file. This allows a DBA to review and modify/optimize the queries and commit the modified file to source control without conflicting with the commits made by the developers.

A related benefit is that source control may be configured in a way to limit the access of DBA to only those files which contain the queries, and deny the access to the rest of the code.

Is it possible to do in PHP?

PHP lacks both partial classes and inner classes, so as is, it cannot be implemented in PHP.

You can create a separate file with a separate static class (DemoQueries) containing the constants, given that the class will be accessible from everywhere. Moreover, in order to avoid polluting the global scope, you can put all query classes in a dedicated namespace. This will create a rather verbose syntax, but I doubt you can avoid the verbosity:

```<code>namespace Data {
    public class Demo inherit DataRepository {
        public function LoadStuff($categoryId) {
            $query = \Queries\Demo::$LoadStuff;
            // Do the stuff with the query.
        }

        // Other methods go here.
    }
}

namespace Queries {
    public static class Demo {
        public const $LoadStuff = '...';

        // Other queries go here.
    }
}
</code>```

Title: Should database queries be abstracted out of the page itself?

Body:
When writing page generation in PHP, I often find myself writing a set of files littered with database queries. For example, I might have a query to fetch some data about a post directly from the database to display on a page, like this:

```<code>$statement = $db->prepare('SELECT * FROM posts WHERE id=:id');
$statement->bindValue(':id', $id, PDO::PARAM_INT);
$statement->execute();
$post = $statement->fetch(PDO::FETCH_ASSOC);
$content = $post['content']
// do something with the content
</code>```

These quick, one-off queries are usually small, but I sometimes end up with large portions of database interaction code which begins to look pretty messy.

In some cases, I've solved this problem by creating a simple library of functions to handle my post-related db queries, shortening that block of code to a simple:

```<code>$content = post_get_content($id);
</code>```

And that's great. Or at least it is until I need to do something else. Maybe I need to get the five most recent posts to display in a list. Well, I could always add another function:

```<code>$recent_posts = post_get_recent(5);
foreach ($recent_posts as $post) { ... }
</code>```

But that ends up using a SELECT * query, which I usually really don't need anyway, but is often too complicated to reasonably abstract. I eventually end up with either a massive library of database interaction functions for every single use case, or a series of messy queries inside every page's code. And even once I've built these libraries, I'll find myself needing to do one tiny join that I hadn't used before, and I suddenly need to write another highly-specialized function to do the job.

Sure, I could use the functions for general use cases and queries for specific interactions, but as soon as I start writing raw queries I begin to slip back into direct access for everything. Either that, or I'll get lazy and will start doing things in PHP loops that should really be done directly in the MySQL queries, anyway.

I'd like to ask those more experienced with writing internet applications: is the maintainability boost worth the extra lines of code and possible inefficiencies that the abstractions may introduce? Or is simply using direct query strings an acceptable method for handling database interactions?

Body:
The pattern I use for most middle-scale projects is the following one:

All the SQL queries are put apart from the server-side code, in a separate location.

Working with C#, it means using partial classes, i.e. putting the queries in a separate file, given that those queries will be accessible from a single class (see the code below).

Those SQL queries are constants. This is important, since it prevents the temptation of building SQL queries on the fly (thus increasing the risk of SQL injection and at the same time making it more difficult to review the queries later).

Current approach in C#

Example:

// Demo.cs
public partial class Demo : DataRepository
{
    public IEnumerable<Stuff> LoadStuff(int categoryId)
    {
        return this
            .Query(Queries.LoadStuff)
            .With(new { CategoryId = categoryId })
            .ReadRows<Stuff>();
    }

    // Other methods go here.
}

public partial class Demo
{
    private static class Queries
    {
        public const string LoadStuff = @"
select top 100 [StuffId], [SomeText]
    from [Schema].[Table]
    where [CategoryId] = @CategoryId
    order by [CreationUtcTime]";

        // Other queries go here.
    }
}

This approach has a benefit of having the queries are in a separate file. This allows a DBA to review and modify/optimize the queries and commit the modified file to source control without conflicting with the commits made by the developers.

A related benefit is that source control may be configured in a way to limit the access of DBA to only those files which contain the queries, and deny the access to the rest of the code.

Is it possible to do in PHP?

PHP lacks both partial classes and inner classes, so as is, it cannot be implemented in PHP.

You can create a separate file with a separate static class (DemoQueries) containing the constants, given that the class will be accessible from everywhere. Moreover, in order to avoid polluting the global scope, you can put all query classes in a dedicated namespace. This will create a rather verbose syntax, but I doubt you can avoid the verbosity:

namespace Data {
    public class Demo inherit DataRepository {
        public function LoadStuff($categoryId) {
            $query = \Queries\Demo::$LoadStuff;
            // Do the stuff with the query.
        }

        // Other methods go here.
    }
}

namespace Queries {
    public static class Demo {
        public const $LoadStuff = '...';

        // Other queries go here.
    }
}


答:
Separation of Concerns is a principle worth reading about, see the Wikipedia article on it.

http://en.wikipedia.org/wiki/Separation_of_concerns

Another principle worth reading about is Coupling:

http://en.wikipedia.org/wiki/Coupling_(computer_science)

You have two distinct concerns, one is the marshaling of the data from the database and the second is the rendering of that data. In a really simple applications there’s probably little to worry about, you’ve tightly coupled your database access and management layer with your rendering layer but for small apps this is no big deal. The problem is that web applications tend to evolve and if you ever want to scale a web app up, in any way ie performance or functionality, then you run into some problems.

Lets say that you’re generating a web page of user-generated comments. Along comes the pointy haired boss and asks you to start supporting Native Apps ie iPhone/Android etc. We need some JSON output, you now need to extract the rendering code out that was generating HTML. When you’ve done this you’ve now got a data access library with two rendering engines and everything’s fine, you scaled functionally. You may even have managed to keep everything separate ie business logic from rendering.

Along comes the boss and tells you that he has a customer who wants to display the posts on their website, they need XML and they need about 5000 requests per second peak performance. Now you need to generate XML/JSON/HTML. You can separate out your rendering again, same as before. However you now need to add 100 servers to comfortably get the performance you need. Now your database is being hit from 100 servers with possibly dozens of connections per server, each of which is directly exposed to three different apps with different requirements and different queries etc. Having the database access on each frontend machine is a security risk and a growing one but I won’t go there. Now you need to scale for performance, each app has different caching requirements ie different concerns. You can try and manage this in one tightly coupled layer ie your database access/business logic/rendering layer. The concerns of each layer are now starting to get in the way of each other ie the caching requirements of the data from the database could be very different than the rendering layer, the logic that you have in the business layer is likely to bleed into the SQL ie move backwards or it could bleed forward into the rendering layer, this is one of the biggest problems I’ve seen with having everything in one layer, it’s like pouring reinforced concrete into your application and not in a good way.

There are standard ways to approach these types of issues ie HTTP caching of the web services (squid/yts etc). Application level caching within the web services themselves with something like memcached/redis. You will also run into issues as you start to scale out your database ie multiple read hosts and one master, or sharded data across hosts. You don’t want 100 hosts managing various connections to your database that differ based on write or read requests or in a sharded database if a user “usera” hashes into “[table/database]foo” for all write requests.

Separation of concerns is your friend, choosing when and where to do it is an architectural decision and a bit of an art. Avoid tight coupling of anything that will evolve to have very different requirements. There are a bunch of other reasons for keeping things separate ie it simplifies testing, deployment of changes, security, reuse, flexibility etc.


问:
what is difference in section and subreport, where to use multiple sections?
Please share your knowledge about these Crystal Reports concepts.

I want to know what is difference in section and sub report? I know about default sections and we can add new sections into report.

What is purpose of a subreport? when should we use a subreport instead of a section?

Where should we use multiple detail sections in report?

Are sections used to carry a "Can grow" field that will be bringing data dynamically?

答:
1) Difference between Section And Subreport

I guess you have confused the concept of section and subreport.

 - Section refers to the design areas which is used to build your
   report. Page header, report header, details, footer are sections of
   report.

 - Subreport is the report within another report object. Even

   subreports have sections in their report.(Page header and Page

   footers Section is not  there in subreports)

2) Purpose of having Sub report

We use subreports  to combine unrelated report to one, to get and
present different views of same data within a report and also to non
linkable data to coordinate.

3) When Multiple Sections are used.

I found the answer by googling. And the answer is here.

Keeping variable length objects from overwriting each other
When
subreports or other variable length objects are placed above other
objects in one section of the report while the Can Grow option for
the variable length object is toggled on in the Properties view, that
object may overprint objects positioned directly below it unless you
have:

Expanded the section to fit the maximum size of the object.

Spaced the objects, allowing enough space for the first object to
complete printing before the second one begins.

You can eliminate
this overprinting problem by creating multiple sections in an area
and placing objects below the variable length object in their own
section(s). Now, when the report runs, the section with the variable
length object will finish printing before the section below it prints
and you will get the results you want.
Note: Many report objects can
use the Can Grow option and can, therefore, cause overprinting:
•
Text fields
• Formula fields
• Subreports

Eliminating blank lines when fields are empty
It is very common to
have two address lines in a customer table, one for street address
(Address 1), and one that can be used for a suite number or mail stop
(Address 2). Address 1 usually contains a value, but Address 2 is
often blank. If you create a customer list using this data and stack
the fields on top of one another in mailing label format, those
customer records with an empty Address 2 field will print with a
blank line. You can eliminate this blank line either by using
multiple sections, or by suppressing blank lines.

To eliminate blank
lines by using multiple sections
a. Create two new Body sections so
that you have a total of three.
b. Place the Address 2 field in the
middle section and the other data in the sections above and below it
as you want it to appear in the report.
c. In the Report Structure
Panel, highlight the second section.
d. In the Properties view, set
Suppress if Blank to True.   Now, when the report prints, if the
Address 2 section is blank, the program will not print it and you
will not get unwanted blank lines in the report.

Adding blank lines conditionally
Use multiple sections to print a
blank line on your report under specific conditions. For example,

you may want to insert a blank line after every fifth record in the

report.
 To add blank lines conditionally

1. Create two Body sections.

2. Place the report detail data in the top section.

3. Right-click the second section and from the context menu, click Conditional Formulas.

4. Select Suppress and then click OK.

5. Enter the following formula:  Remainder (RecordNumber,5) <> 0 This formula divides each record number by 5. If the division

produces a remainder, it suppresses the blank section. But if the

division produces no remainder (which it will for every fifth record
printed), the program prints the second section, thus inserting a

blank line.
Note: To insert a blank line under different conditions,
you can modify your formula appropriately.

4) "Can grow" is an option(check box)  can be set  to sections in order to dynamically format data.

Hope it answers your question!!


答:
Well run open source projects use the same tool sets and patterns of behaviour that good closed source projects do.  The difference is that in the open source model you can have many more eyes on the design and the code.

So for the two open source projects I'm heavily involved with, we:

Have JIRA as a feature request and bug tracking system
** We roadmap the items listed in JIRA

We hold collaborative design discussions on mailing lists and IRC

We have code reviews

For new joiners, we ask that they submit patches until we are comfortable with their level of code quality and familiarity with the code base

We ensure that documentation is written as part of completing some code

We use source control and have feature branches and maintenance branches

We run a CI server

See http://www.producingoss.com for a guide on how to run a successful open source project

Body:
How do open source projects maintain quality?
What keeps the projects from people with relatively little programming experience checking in poor quality codes?</p>


问:
Application Logic – which of the two definitions is correct?
This is my understanding of the Application Layer:

• It implements Application logic

• this layer contains Application Services, which are used by external consumers to talk to your application

• Application Services are coarse-grained and orchestrate operations which map directly to use cases ( hence also the term Workflow Services )

1)

From:

Application Logic is mostly workflow logic. It is the application
  specific coordination of domain and infrastructure components
  according to the requirements of that particular application.

From:

Let's start a company, shall we? Sapient Grey will be primarily a
  think tank, but with an in-house development group with the
  capabilities to make the visions of the core committee a reality. Our
  corporate motto, "Sapient Grey is People..." will be burnished in
  giant brazen letters alongside a customized version of Rodin's famous
  sculpture "The Thinker", all of which will adorn the east-facing side
  of our brand new ten story red granite office building.... Oh, wait.
  We don't have an office building yet. Okay then, so we'll hire an
  architect to design our office building, being sure to include a
  private elevator and an elaborate zen-style atrium or courtyard in the
  center. In the meantime, while the building is being designed and
  constructed, you and I and our other elite colleagues will fly
  ourselves to Tahiti to brainstorm Sapient Grey's visions, goals,
  agenda, and lay out a detailed business plan.

Our architect is creating detailed blueprints for the office building, figuring out how
  the plumbing will need to be laid out, how the electrical systems will
  be segregated and tied together, how the interoffice communication
  system will be organized, and how we will implement security at all
  levels. The systems and designs that our building architect is
  handling is a precise analogy to what "Application Logic" is within a
  web application. How security is implemented, how we will manage and
  access state and persistence, how we will handle storage and retrieval
  of data....this is application logic. Like our office building, which
  when complete could house and accommodate anything from an elite night
  club to an investment firm, the application logic is independent of
  the actual business logic that executes within it.

a) The above quotes are two different definitions of the term Application Logic and as such  it appears they just happen to use the same term (ie Application logic) to describe two different concepts. Thus, does only the the first definition describe the logic contained in Application layer, while the latter definition is describing a different kind of logic?

b) If indeed both definitions describe the logic in Application layer, then wouldn't this mean that  Application layer performs two tasks: orchestrating operations that map directly to use cases and executing non-business related logic (such as security, caching etc)?

答:
I am the one that posted the article in the first quote and I must admit I wasn't quite clear in that "definition" of application logic. When I said "mostly" I should definitely have said "sometimes".

Application Logic (hopefully concentrated in an application layer and not scattered across the BBOM) is any logic that is specific to some application. It is fundamentally different from Domain Logic and Infrastructure Logic in terms of target and re-usability: Domain Logic is the logic solving problems in the domain of interest and it should be totally reusable in applications addressing the same domain context but exposing different features. Infrastructure Logic is about generic technical capabilities that should be reusable in any application from any domain.

Having said that, your application logic can be entirely concentrated in some services exposing a feature-oriented coarse-grained interface, in a procedural fashion if the logic is fairly simple (similar to Fowler's Transaction Script pattern, although the target of this pattern is Domain Logic organization – it can be extended to application logic as well).

On the other hand, if your application logic has a fair degree of complexity (such as complicated dynamic wizard-style flows or the need to restrict user access to certain subsets of domain logic and data function of complicated combinations of permissions assigned to various user roles) it's worth building an object model of the application specific concepts. This object model can sit behind a feature-oriented coarse-grained facade (logical service) but the application logic is not anymore just the orchestration provided by the feature-oriented service but the behavior in the object model behind it as well.

ContentLicense: CC BY-SA 4.0


问:
Container types in Golang
For a non-OOP language like google Go, is it idiomatic to go about implementing new container types using datatypes like arrays or lists so as to implement convenient functionality like contains method which is absent from all in built container types?

答:
The container package currently contains built-in objects for heaps, doubly linked lists, and circular lists. The source code for the container/list package also gives the idiomatic way to iterate over lists. With datatypes so easy to define, I don't think there is any problem in implementing new containers on your own. I would also imagine that as Go matures, it will add additional built-in data structures.

A channel is essentially a FIFO queue; see this source for help on making your own types thread-safe.

Title: Container types in Golang


答:
I don't think this kind of problems have the general solution. Duplicate code will not created if the developers have enough willingness to look up existing code. Also developers could fixed the problems on the spot if they want to.

If the language is C/C++ duplication merge will be easier because of flexibility of linking (one can call any extern functions without prior information). For Java or .NET you may need to devise helper classes and/or utility components.

I usually begin the duplication removing of existing code only if the major errors are arise from the duplicated parts.

Title: How do I prevent unknowningly duplicating code?

Body:
I work on a rather large code base. Hundreds of classes, tons of different files, lots of functionality, takes more than 15 minutes to pull down a fresh copy, etc.

A big problem with such a large code base is that it has quite a few utility methods and such that do the same thing, or has code that doesn't use these utility methods when it could. And also the utility methods aren't just all in one class (because it'd be a huge jumbled mess).

I'm rather new to the code base, but the team lead who's been working on it for years appears to have the same problem. It leads to a lot of code and work duplication, and as such, when something breaks, it's usually broken in 4 copies of basically the same code

How can we curb this pattern? As with most large projects, not all code is documented(though some is) and not all code is... well, clean. But basically, it'd be really nice if we could work on improving the quality in this respect so that in the future we had less code duplication, and things like utility functions were easier to discover.

Also, the utility functions are usually either in some static helper class, in some non-static helper class that works on a single object, or is a static method on the class which it mainly "helps" with.

I had one experiment in adding utility functions as Extension methods(I didn't need any internals of the class, and it definitely was only required in very specific scenarios). This had the effect of preventing cluttering up the primary class and such, but it's not really anymore discoverable unless you already know about it


问:
I've been told HTML is a markup language, C++ is a programming language, what could make that difference?
My programming friends are always telling me that HTML is a markup language and C++ is a programming language. When I ask them what's the difference, they never give me a reasonable answer.

What could make one call C++ a programming language, and HTML not?

答:
A programming language is a notation designed to pass instructions to a machine. By that definition both C++ and HTML are programming languages, as was the notation Joseph Marie Jacquard used in 1801 to program his looms.

However with the proliferation of languages that are used to structure and/or describe data, the definition of a programming language shifted to include only languages that are capable of expressing algorithms. This is the more common definition today and it excludes languages like HTML or XML.

At the heart of the current definition is the concept of Turing completeness. Most programming languages are Turing complete, and Turing completeness is often quoted as the one critical trait that separates a programming language from any other computer language. This is good enough as a general rule of thumb, but not entirely accurate:

Some non Turing complete languages are considered programming languages, for example Charity.

Some languages that are not generally considered programming languages are Turing complete, for example XSLT.

Turing completeness alone doesn't say much about a language's usefulness.

Depending on context, you can pick any definition you want.

Edit:

Let it further be known, an implementation of a language does not confer characteristics onto the language itself, for example: A language's spec may define a turing complete language, someone could implement it haphazardly leaving off turing completeness. This implementation being non-turing complete does not however mean the language itself is not turing complete (rather it likely means that implementation is non-conformant). The details of a language and the details of a particular implementation of a language are to be recognized as separate things, this is why it's inaccurate to call a language interpreted or compiled etc.


问:
Architecting persistence (and other internal systems). Interfaces, composition, pure inheritance or centralization?
Suppose that you need to implement persistence, I think that you're generally limited to four options (correct me if I'm wrong, please)

Each persistant class:

Should implement an interface (IPersistent)

Contains a 'persist-me' object that is a specialized object (or class) that's made only to be used with the class that contains it.

Inherit from Persistent (a base class)

Or you can create a gigantic class (or package) called Database and make your persistence logic there.

What are the advantages and problems that can come from each of one? In a small (5kloc) and algorithmically (or  organisationally) simple app what is probably the best option?

答:
In a small (5kloc) and algorithmically (or organisationally) simple
  app what is probably the best option?

5kloc may seem small, yet if you have to maintain it over time, you will benefit from a clear design and well structured code (read: multiple classes or modules, each one focused to a particular task). This said - without knowing more about your application - my general advice is this:

always strive to factor out persistence from your algorithm code (aka "domain logic"). This keeps your algorithm code clean and simple, and makes the persistence logic easier to maintain. Mixing persistence with algorithm code introduces complexity that will be hard to maintain in the long-run.

implement persistence such that it is well encapsulated. Ideally your domain logic (and all its classes/objects) does not know that it is persisted.

Use a persistence framework (e.g. ORM) if possible, this greatly simplifies the design and reduces the need to write specific code (i.e. SQL, object mapping etc.).

If there are a large number of classes, group them by "inner cohesion", i.e. figure out which classes belong to each other, and organize persistence by group.

In other words, don't centralize all of the persistence logic in one large Database class, but rather centralize by group of classes. This keeps the system design tractable and your code readable.


问:
Why can't Windows services have a GUI?
I was using this feature in earlier Windows release like XP and NT. I was able to run a GUI from a Windows service. But it is not possible in the later versions.

What is the reason behind the removal of this feature? Why can't Windows services have a GUI?

答: Because services are supposed to run in the background without interacting with the user; they may in fact run while no user is logged in.</p>

Title: Why can't Windows services have a GUI?


答:
Interactive services used to be possible, but the service model is that of a process that runs independently of any user. They are designed to be run unattended and therefore shouldn't need a GUI.

Interactive services haven't been available since Windows Vista so should no longer be used.

If you need to interact with the service the page I've linked to recommends creating a separate GUI application that communicates with the service through interprocess communication (IPC) of some sort - e.g. named pipes.

Title: Why can't Windows services have a GUI?

Body:
I was using this feature in earlier Windows release like XP and NT. I was able to run a GUI from a Windows service. But it is not possible in the later versions.

What is the reason behind the removal of this feature? Why can't Windows services have a GUI?


问:
Designing persistence schema for BigTable on AppEngine
I have tried to design the datastore schema for a very small application. That schema would have been very simple, if not trivial, using a relational database with foreign keys, many-to-many relations, joins, etc.

But the problem was that my application was targeted for Google App Engine and I had to design for a database that was not relational. At the end I gave up.

Is there a book or an article that describes design principles for applications that are meant for such databases?

The books that I have found are about programming for App Engine and they don't spend many words about database design principles.

答:
In general, creating a data model for a NoSQL database is no different than for any other database (remember No stands for NotOnly). You should still look for cohesive objects that you can name and describe as:

entities (or in some cases: documents)

attributes

associations/relationships between entities

The difference to a traditional relational model may come from particularities of the NoSQL DB used, or the scenario you are trying to achieve (i.e. optimize for frequent reads, writes, udpates). For example, in a GAE application you can optimize read access by explicitely modeling parent/child relationships, keep data consistent by entity groups, and multi-valued properties to improve multi-entity join operations.

There is some good documentation on this (related to GAE) by the folks at Google and others:

Datastore Overview (Python)

Entities, properties and keys (Java)

Data Modeling and Scalability in Google App Engine (Python examples)

BTW, GAE also provides support for relational DBs based on MySQL


答:
Yes it was possible and it worked. When you logged in you got the interface of the application. It was very useful for older applications which don't have a service available but still need to run on the server. Though it was not the most stable solution. It became running as the user which could click it away or logout. That was not very nice.

Now everybody develops native services and adds an application or log to manage the service. That's a good design pattern and is now being used most of the time.

So see it more as legacy that it was possible.

Title: Why can't Windows services have a GUI?


答:
That really depends on the size of the developer base, and what back yard you happen to be playing in.

How either of those are determined mostly depends on the skills of the founding developer(s).

First, realize that writing code and pushing it into the wild for the whole world to critique and review takes a special kind of person. That person might not be very confident in their abilities, but they are willing to publish their code anyway. Someone else might be extremely confident. Both people have the same goals:

Release something that seems useful

Get help from other programmers

There may be underlying financial reasons, but the above tends to be true.

There may be other motivations in the mix. I know people who spend an enormous amount of time re-writing proprietary applications under an OSI approved license (usually the 3 clause BSD or GPL). I know other people who can't stand GPL2+ libraries and work to re-write them in order to release them under a less restrictive license.

In any event, you have lots of people writing and publishing code for various reasons.

In my experience, (really) bad code gets committed due to the following reasons:

The original author found contributors that exceed their skill level. They don't know a bad patch from a good one.

The original author wants to stick it to (insert whatever man here) and is happy to have some help and a fellow idealist to e-mail

The original author trusted a part of the code to someone who made some bad decisions on what actually gets accepted, or didn't really look at what was being proposed.

Lets break these down a bit:

On the first point, the original author probably hoped to learn something in the process of releasing their work. That's not in any way bad, but if you have a small development community it can become toxic. Think about it, you have a thick enough skin to release your stuff, you get a patch that blows your mind, is your skin now thick enough to admit that you have no idea what the patch actually does? That happens quite a bit. If you have more eyeballs watching things, it helps. So let's say the first root of toxic changes is ego.

Additionally, you might just get tired of fighting an otherwise great contributor on a single point and just say 'screw it', even if you understand the patches.

On the second point, stuff that is written to fill an idealistic void (at least early on) is of lesser quality than something written to fill a technical void, at least in my experience. For the most part, the GNU project is an exception to this rule, they have been producing software that runs predictably and consistently on a variety of architectures for years.

You won't see a lot of revengeware in the wild, it doesn't last very long. I have been part of projects that were started explicitly to stick it to the man, and I've quickly left them. This brings us to the second source of toxic changes, no real focus.

Finally, you get to the point that a project has really taken off. The original author is not only skilled enough, but trusts their skills enough to ward off toxic patches. The project grows, the code base grows and more and more trusted lieutenants are brought on to help manage contributions. The original author has final say, if they want it, but trusts their inner circle to effectively look after the parts that they maintain.

People do odd things. I can't count the number of nervous breakdowns that I've witnessed on public mailing lists on both hands. People get burned out, develop drinking problems, sometimes drug problems or all out vanish. Their spouses leave them, their homes burn down, feces occurs. However, by this time, you should have enough critical eyes on stuff to catch that.

This brings us to the third (at least in my experience) reason why toxic code gets put out into the wild - a lack of community oversight. This happens mostly in projects where users outnumber actual contributors by 100:1 or more. You have plenty of eye balls, but none of them know what they're looking at.

Not listed, but finally, the original developer may have burned out years ago. When / if that happens, a project loses passion.

Beyond that, other things happen. Companies get bought (we're seeing the aftermath of that now with OpenOffice / OpenSolaris).

Title: How do open source projects maintain quality?


答:
Two simple measures:

Code reviews (already mentioned by others) before each check in. You do not need to explain every detail of what you check in, but the reviewer should get an idea of the changes that are being checked in. You can program your RCS to reject check-ins whose check-in text does not contain a tag "REVIEWED BY: ...".

Agree with the rest of the team that if a check-in breaks any unit tests, the developer who has performed the check-in must fix the code until those unit tests are green again (possible measure: write a bug and assign it to him / her). As an alternative: if a team member detects a check-in that breaks the unit tests, he or she can revert the changes. The author of the wrong check-in is not allowed to check-in again as long as the problem is not fixed locally (unit tests are green locally).

NOTE

Point 2 has been edited taking into account gnat's comment.


答:
Mainly security reasons.

As I understand it, when a windows service creates GUI controls such as a MessageBox, they were normally only seen in the session that the services runs in ie Session 0 which also used to be the first user logged on locally or by someone logging on using mstsc /admin. Hence this user would see these controls and could interact with the service.

But for security reasons, Session 0 is now reserved and the first user to log on will be given a new session and hence not see the GUI Controls.

Since this breaks quite a lot of services, for compatibility, there is a process (see this MSDN blog)  that attempts to detect if any messages are being displayed and popups with a warning 'A program running on this computer is trying to display a message' and allows you to view or ignore the message.

Microsoft have a WhitePaper on this subject which you can download from here

I would also suspect that another minor reason is because the feature was misused/misunderstood and led to bad designs. For example, I used to have an old server with a third-party service that displayed some notifications/errors using a message box rather than writing to the event log. But I never logged on locally and rarely logged in in admin mode and hence I would not see the messages.

Title: Why can't Windows services have a GUI?


答:
The services are meant for un attended operations , mainly in the background.The name service itself means act as a server for some client applications or other services which consumes this service.
So MS might want now to stick to the basics and want to draw some clear distinction between services and Apps.So apps keeps the uses busy and let services serve their purpose silently.
While nail cutter is there why go for kitchen knife to cut nils?</p>

Title: Why can't Windows services have a GUI?


问:
Mingling DB transactions and logging from a design perspective
Say we have a view page where users perform actions in multiple steps, some of these actions would involve DB operations with transactions (the snippets are in pseudo-code like from):

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Call ActionX

    Step 3:
        ...

ActionX: # can be called from different points in the view
    ...
    Begin Transaction
    DB ops
    End Transaction
</code>```

Say we want to log the user progress in the view (or save some states) in a persistent manner in the DB, so that if the program/app is interrupted we can re-establish the state to the last user action inside a view:

```<code>View1:
    Step 1:
        ...
        Logger.log('view1-step1-done')

    Step 2:
        ...
        Call ActionX
        Logger.log('view1-step2-done')

    Step 3:
        ...
        Logger.log('view1-step3-done')
</code>```

Now ideally, we would want to have the persistent logging and the DB based transactional  actions to be both done in the same DB transaction, because we don't want to create an inconsistent state where an action is performed
but is not reflected in the log state, or vice versa.

The question is: how to achieve the said goal with minimum inter-dependency and SOC. Some suggestions for example:

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Begin Transaction
        Call ActionX    # begin/end transaction statements will be removed from ActionX
        Logger.log('view1-step3-done')
        End Transaction

    Step 3:
        ...
</code>```

Don't like this because the handling of transactions belongs naturally in the action itself.

Or, another one:

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Call ActionX (logMsg='view1-step3-done')

    Step 3:
        ...

ActionX (logMsg):
    ...
    Begin Transaction
    DB ops
    Logger.log(logMsg)
    End Transaction
</code>```

Don't like this one either. The log message handling doesn't belong in the actions.

答:
The primary guidance for this question is to separate out the responsibilities.

It appears that you are trying to link an Action's transactional state with the Log's transactional state, and I think that's a mistake.  Record the Action changes based upon the Action.  Record the Log status based upon the resulting (returned) status.  If the Action succeeds, then Log a success status message.  Likewise, if the Action failed, then Log an error message to that effect.

Since your log messages appear to be indicating status from the Views, then it is the Views' responsibility to handling the logging.

If the log messages are related to the internal aspects of the Action, then the Action should take the responsibility of logging.

Please keep in mind that those two positions are not exclusive of each other.  You might find that you need to log both the Views' progress as well as internal aspects of the Action.  At that point, you would have both areas (Views and Action) making logging calls.


问:
Design question about a concurrent forking server
I'm in the early stages of designing a client/server application.  The clients will be batch programs that read a file of customer contact data (name, address, email address, phone no's) and pass these components to the server, which will add them (if not already present) to corresponding mySQL tables  and return id's for each component.  In order to boost performance, the server will have spawned four "manager" servers, each tasked with looking up and possibly adding a new row, and will pass the four components via IPC to those managers so that they can work concurrently.

In other words

One "master server" that does nothing but listen for a connection from a batch job, and fork/exec a "slave" process,

Four "managers" that read from a socket, do a table lookup and possibly add a row, and write back an id,

One "slave" process for each connected client, spawned by the master when a new connection arrives from a client, which converses with the batch job: receiving a customer contact record, sending components to each of the managers, waiting for all of the managers to respond with the id's they've computed, and sending a summary record back to the client before looping back to receive the next record.

(The processing is a bit more involved than I've described- there are actually eight managers, and the results from the first four need to be completely gathered before invoking the next three managers, which in turn must all complete before calling the final manager.  But that's just a simple process with several sequential stages, each of which involves farming out concurrent work and waiting for it all to finish.)

In discussing this with another member of the team, I was asked "why have the master server and the slave servers?  why not have the client make separate connections directly with those manager processes?"

I haven't got a really good objection: each client could essentially implement the slave logic directly and create eight simultaneous connections to the manager servers.  I have a feeling that's not the best approach - that somehow it might be important to have some centralized control to robustly deal with failures and errors, or to accumulate statistics about the server as a whole.  But I've no prior experience building a full-scale, production-worthy client/server app.

I'd be very interested in hearing the opinions of those with prior experience building apps of this nature.

UPDATE 1: One advantage:  If the client process abruptly crashed or was canceled, the slave process would stay alive, could detect that the client had gone away, would have complete knowledge of the job state, and could ensure data integrity by completing (or backing out) the current unit of work.  It could bring an orderly end to a failure.

答:
In short, the answer to your colleague is "encapsulation."

What are you going to do when you need to spin up a ninth manager?  Or more slave processes per client?  Or you need to adjust the interaction logic just enough that it would force updating and invalidating all of the existing clients?  Do you have full control over all of the clients in order to do that?

It doesn't sound like any of the processing needs to be done by the clients, so they shouldn't.

And, in theory, you have control over the master / managers / slaves, so you can trust that code a little bit more than you can with the client.  Even though you may be writing / publishing the clients you want to look at it from a security point of view as well.  Clients are generally less trustworthy than the server components because of deployment and being on systems outside of those you control.  You may also have to support downlevel client versions which can really foul up your ability to make changes if the logic resides within the client.

You're on the right path for a client / server environment.  Stick to design you've started and don't provide inappropriate access to the clients.


答:
A nested transaction would work if your database supports them.</p>

```<code>View 1:
Step 1:
    ...

Step 2:
    ...
    Begin Transaction
    Call ActionX    # begin/end transaction statements will be removed from ActionX
    Logger.log('view1-step2-done')
    End Transaction

Step 3:
    ...

ActionX ():
...
Begin Transaction
DB ops
End Transaction
</code>```

Title: Mingling DB transactions and logging from a design perspective

Body:
Say we have a view page where users perform actions in multiple steps, some of these actions would involve DB operations with transactions (the snippets are in pseudo-code like from):

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Call ActionX

    Step 3:
        ...

ActionX: # can be called from different points in the view
    ...
    Begin Transaction
    DB ops
    End Transaction
</code>```

Say we want to log the user progress in the view (or save some states) in a persistent manner in the DB, so that if the program/app is interrupted we can re-establish the state to the last user action inside a view:

```<code>View1:
    Step 1:
        ...
        Logger.log('view1-step1-done')

    Step 2:
        ...
        Call ActionX
        Logger.log('view1-step2-done')

    Step 3:
        ...
        Logger.log('view1-step3-done')
</code>```

Now ideally, we would want to have the persistent logging and the DB based transactional  actions to be both done in the same DB transaction, because we don't want to create an inconsistent state where an action is performed
but is not reflected in the log state, or vice versa.

The question is: how to achieve the said goal with minimum inter-dependency and SOC. Some suggestions for example:

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Begin Transaction
        Call ActionX    # begin/end transaction statements will be removed from ActionX
        Logger.log('view1-step3-done')
        End Transaction

    Step 3:
        ...
</code>```

Don't like this because the handling of transactions belongs naturally in the action itself.

Or, another one:

```<code>View 1:
    Step 1:
        ...

    Step 2:
        ...
        Call ActionX (logMsg='view1-step3-done')

    Step 3:
        ...

ActionX (logMsg):
    ...
    Begin Transaction
    DB ops
    Logger.log(logMsg)
    End Transaction
</code>```

Don't like this one either. The log message handling doesn't belong in the actions.

Body:
A nested transaction would work if your database supports them.

View 1:
Step 1:
    ...

Step 2:
    ...
    Begin Transaction
    Call ActionX    # begin/end transaction statements will be removed from ActionX
    Logger.log('view1-step2-done')
    End Transaction

Step 3:
    ...

ActionX ():
...
Begin Transaction
DB ops
End Transaction


答:
You need to implement a Continuous Integration (CI) system like TeamCity.  It should not be some developer a few days later noticing the problem.  With a CI system as soon as a check-in occurs the code is automatically built and the automated tests are executed.  Within minutes of the check-in the CI system will alert everyone that the build has been broken and who did the check-in that caused it.

This way it is all completely objective and there is no finger pointing about who is at fault.  Unlike developers the CI system is using only that latest code from source control to do its testing.  There are no local changes and no funky configuration differences.  Most systems have a tray icon that turns red when the build is broken.  All developers should have that icon installed and keep track if the build is OK or broken.


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答:
In theory I think it makes sense to encapsulate the database connection logic to make it more easily reusable, but as the link below argues, our modern frameworks essentially take care of this now.

Reconsidering the Repository Pattern

OwnerDisplayName: StringBuilder

OwnerDisplayName: Splendor


答:
I don't see any reason for the Repository pattern to not work with Entity Framework.  Repository pattern is an abstraction layer you put on your data access layer. Your data access layer can be anything from pure ADO.NET stored procedures to Entity Framework or an XML file.

In large systems, where you have data coming from different sources (database/XML/web service), it is good to have an abstraction layer. The Repository pattern works well in this scenario. I do not believe that Entity Framework is enough abstraction to hide what goes on behind the scenes.

I have used the Repository pattern with Entity Framework as my data access layer method and am yet to face a problem.

Another advantage of abstracting the DbContext with a Repository is unit-testability. You can have your IRepository interface to which has 2 implementations, one (the real Repository) which uses DbContext to talk to the database and the second, FakeRepository which can return in-memory objects/mocked data. This makes your IRepository unit-testable, thus other parts of code which uses IRepository.

```<code>public interface IRepository
{
  IEnumerable<CustomerDto> GetCustomers();
}
public EFRepository : IRepository
{
  private YourDbContext db;
  private EFRepository()
  {
    db = new YourDbContext();
  }
  public IEnumerable<CustomerDto> GetCustomers()
  {
    return db.Customers.Select(f=>new CustomerDto { Id=f.Id, Name =f.Name}).ToList();
  }
}
public MockRepository : IRepository
{
  public IEnumerable<CustomerDto> GetCustomers()
  {
    // to do : return a mock list of Customers
    // Or you may even use a mocking framework like Moq
  }
}
</code>```

Now using DI, you get the implementation

```<code>public class SomeService
{
  IRepository repo;
  public SomeService(IRepository repo)
  {
     this.repo = repo;
  }
  public void SomeMethod()
  {
    //use this.repo as needed
  }
}
</code>```

Title: Why shouldn't I use the repository pattern with Entity Framework?

Body: During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

Body:
I don't see any reason for the Repository pattern to not work with Entity Framework.  Repository pattern is an abstraction layer you put on your data access layer. Your data access layer can be anything from pure ADO.NET stored procedures to Entity Framework or an XML file.

In large systems, where you have data coming from different sources (database/XML/web service), it is good to have an abstraction layer. The Repository pattern works well in this scenario. I do not believe that Entity Framework is enough abstraction to hide what goes on behind the scenes.

I have used the Repository pattern with Entity Framework as my data access layer method and am yet to face a problem.

Another advantage of abstracting the DbContext with a Repository is unit-testability. You can have your IRepository interface to which has 2 implementations, one (the real Repository) which uses DbContext to talk to the database and the second, FakeRepository which can return in-memory objects/mocked data. This makes your IRepository unit-testable, thus other parts of code which uses IRepository.

public interface IRepository
{
  IEnumerable<CustomerDto> GetCustomers();
}
public EFRepository : IRepository
{
  private YourDbContext db;
  private EFRepository()
  {
    db = new YourDbContext();
  }
  public IEnumerable<CustomerDto> GetCustomers()
  {
    return db.Customers.Select(f=>new CustomerDto { Id=f.Id, Name =f.Name}).ToList();
  }
}
public MockRepository : IRepository
{
  public IEnumerable<CustomerDto> GetCustomers()
  {
    // to do : return a mock list of Customers
    // Or you may even use a mocking framework like Moq
  }
}

Now using DI, you get the implementation

public class SomeService
{
  IRepository repo;
  public SomeService(IRepository repo)
  {
     this.repo = repo;
  }
  public void SomeMethod()
  {
    //use this.repo as needed
  }
}

OwnerDisplayName: Shyju


问:
How to maintain nearly identical internal/external programs without having separate codebase for each?
I have a program I'm working on that my company uses internally, but is also sent to vendors.  The vendor version will be identical, except that it will be missing some features, and use an installer. I only have to remove 2 lines from an XML file, and it's good for external use.

Is there some "typical" method to create a project like this without having to maintain separate codebases for each project?

If it makes any difference, program is written in C#, developed using Visual Studio 2010, compiled as a dll, runs on Windows 7.

答:
This sounds like a weak approach to including / excluding functionality. All it takes is one customer to backward-engineer your program and figure out which XML elements to add and they have access to the functionality you want to hide.

A better approach is to have a plug-in system, where the software looks for an assembly that includes your extra functionality, but fails gracefully if that assembly isn't there.

This way you don't need a separate codebase. You simply install the same software everywhere and your plugin locally.


答:
I would have licensing system where based on the Licence you have different modules get loaded\activated.

But the entire code base is always the same.

Title: How to maintain nearly identical internal/external programs without having separate codebase for each?

Body:
I have a program I'm working on that my company uses internally, but is also sent to vendors.  The vendor version will be identical, except that it will be missing some features, and use an installer. I only have to remove 2 lines from an XML file, and it's good for external use.

Is there some "typical" method to create a project like this without having to maintain separate codebases for each project?

If it makes any difference, program is written in C#, developed using Visual Studio 2010, compiled as a dll, runs on Windows 7.


问:
Splitting big request in multiple small ajax requests
I am unsure regarding the scalability of the following model. I have little experience with large systems, big number of requests and so on but I'm trying to build some features considering scalability first.

In my scenario there is a user page which contains data for:

User's details (name, location, workplace ...)

User's activity (blog posts, comments...)

User statistics (rating, number of friends...)

In order to show all this on the same page, for a request there will be at least 3 different database queries on the back-end. In some cases, I imagine that those queries will be running quite a wile, therefore the user experience may suffer while waiting between requests.

This is why I decided to run only step 1 (User's details) as a normal request. After the response is received, two ajax requests are sent for steps 2 and 3. When those responses are received, I only place the data in the destined wrappers.

For me at least this makes more sense. However there are 3 requests instead of one for every user page view.
Will this affect the system on the long term? I'm assuming that this kind of approach requires more resources but is this trade of UX for resources a good dial or should I stick to one plain big request?

答:
In absolute speed, this solution would be slower. However, in perceived speed it can be faster.

Users don't read the whole page all at once, they start by reading what they're most interested in, then may switch to other parts of the page. Which means the user, in most cases, won't even realize some parts of the screen aren't fully loaded yet.

In your case, presumably :

User details will be read first if the user is unknown, activity will be read first if the user is known

Statistics will be read last (if at all)

So you you can improve perceived speed by showing either user details or activity or both, and loading statistics afterwards.


问:
what is the best way to ensure accountability in code checkins?
Note:  after writing this I realize that this question is perhaps philosophical, but I'm interested in how the industry handles this scenario regardless.

I have recently been working with a code base that is not yet as testable as it should be.  I've seen some junior developers check in code that breaks use cases, which is usually identified by another developer a few days after the check-in.

Assuming that we can't achieve code coverage yet, are there technical solutions for holding developers accountable for bad check-ins in addition to a non-technical approach; discussing the commit and having the dev address the issue in a new commit.

答:
Either of the following should reduce the risk of a junior committing bad code drastically :

Pair programming, preferably with a senior developer as a navigator

Pre-commit code reviews by a senior developer

A nice thing about these is that they are collaboration-oriented, not blame-oriented, which IMO is definitely something you should favor when integrating junior programmers.


问:
How to refer to specific areas of code in documentation?
I'm about to leave a project, and before I go my boss has asked for me to document code (I've not documented very well).  It's not a big deal, the project is not terribly complex.  But I'm finding places in my documentation where I would like to say, "Notice on line XYZ that such-and-such happens."

In this case, it doesn't make sense to refer to a specific line number, since adding or deleting a single line of code would immediately outdate the documentation.  Is there some best-practice for referring to a specific line of code without referring to it by line number?

I've considered littering the code with comments like:

```<code>/* linetag 38FECD4F */
</code>```

Where "38FECD4F" is some unique tag for that specific line.  Then I can put in the documentation, "On the line tagged '38FECD4F', notice that such-and-such happens."

Any other ideas?  I feel like it's generally better to document code units as a whole, rather than specific portions of them, but in the case of this particular project there are LONG swaths of procedural code, which have never been refactored into smaller units.

答:
I suggest you take a different approach, other than linking from some code-external documentation to code:

add comments to your code, using a tool like doxygen.

should there be a need to explain some concept in more detail than is suitable within the (newly created) code's documentation, you can always create a separate document and link to that.

This way you can easily generate the documentation as a web page or as a PDF, and it stays consistent with the code. Using some artificial tags will become very difficult to maintain and even more difficult to understand for the uninitiated.


问:
Static Tables vs Dynamic Entity Attributes Storage Configurations
I am trying to figure out a better way to decide table storage configurations whether it will use static configurations using tables or dynamic configurations using EAV (entity-attribute-value)

When creating database tables, forms, and reports, when do you decide that a program should use a normal database (wherein everything is statically configured, possibly final) or use entity-attribute-values (wherein all of the data are dynamic and can be customized)?

Does it all depend on the client/people using it? Is static-table-customized-programs only applicable for small and medium businesses? and dynamic-eav-customizable-field-programs (like Quickbooks) only for the general public or big businesses wherein they don't want another programmer to tamper again with their software?

答:
Use EAV when the number of possible attributes is large, but the number of actual values is relatively small and cannot be predicted with any certainty.

An example of this is symptom capture for medical records.  There can literally be hundreds if not thousands of possible symptoms, but the actual number of symptoms that any one patient might have is small relative to the total symptom pool.

In this scenario, it is impractical to have one column in the database for every possible symptom; many databases are not even capable of storing that many columns. Nor can you predict with any certainty how many symptoms any given patient might have, so you can't just add an arbitrary number of columns to the database for actual symptoms.

If you do either of these things, you will find that most of your database is empty, because you will have a vast swath of fields that are not used.  It's a sparse matrix, basically.  This is why spreadsheets are not actually stored as an array but as a sparse matrix, because there are so many empty cells otherwise.

The difficulty with EAV is in flattening the sparse matrix into a conventional format for reporting and other purposes, which is why such reports are typically done vertically, rather than horizontally.  An invoice is an example of such a report: the product names are never listed out as columns, but rather appear as rows in the line item detail.

This is why sales inventory can also be considered a form of EAV (your customer is not going to buy every one of your products, but only a select few).


答:
If I understand it right, you seem to have a unique problem. What you want to do it refer to a specific line of code in comments which are written in some other portion of the same code.

I don't usually come across such scenarios where I need to refer to an exect line # in some comment written elsewhere -- generally code is documented right where it is written.

I don't know of any standard way to do this -- but off the top of my head...

You can refer to portions of code via it's context -- i.e. things surrounding them.

Notice above the definition of func1() that such-and-such happens

Note that just after the for loop that iterates over recordXYZItr, that we are also calling the method gc()

Caution: In the method yahoo(), right after the declaration of variable PQ, we are also swapping the values in A and B, so the mapABC object there also needs to be copied

Another way is to add descriptive tags. Instead of something like 38FECD4F, you can say Some XYZ implementation or BUGFIX 1474, and then refer to that somewhere else.

Title: How to refer to specific areas of code in documentation?

Body:
I'm about to leave a project, and before I go my boss has asked for me to document code (I've not documented very well).  It's not a big deal, the project is not terribly complex.  But I'm finding places in my documentation where I would like to say, "Notice on line XYZ that such-and-such happens."

In this case, it doesn't make sense to refer to a specific line number, since adding or deleting a single line of code would immediately outdate the documentation.  Is there some best-practice for referring to a specific line of code without referring to it by line number?

I've considered littering the code with comments like:

```<code>/* linetag 38FECD4F */
</code>```

Where "38FECD4F" is some unique tag for that specific line.  Then I can put in the documentation, "On the line tagged '38FECD4F', notice that such-and-such happens."

Any other ideas?  I feel like it's generally better to document code units as a whole, rather than specific portions of them, but in the case of this particular project there are LONG swaths of procedural code, which have never been refactored into smaller units.


答:
Is there some "typical" method to create a project like this without
  having to maintain separate codebases for each project?

More complex approaches (configuration, plugins etc.) have been described. Yet for your relatively simple case you may be better off using a straight forward approach, that is automate what you do manually:

Maintain one code base

Add a "config" folder that has /vendor and /internal subdirectories, each one containing the specific XML file to be included in each version.

Create a build script that accepts -internal or -vendor as a parameter

The build script will then create the shippable software (i.e. the binary plus configuration file) by simply copying the respective XML to the right location.


问:
What discipline does Computer Science belong to?
Is Computer Science science, applied mathematics, engineering, art, philosophy? "Other"?

To provide background, here is Steven Wartik's blog posting for Scientific American titled "I'm not a real scientist, and that's okay." The article covers some good topics for this question, but it leaves open more than it answers.

If you can think of the discipline, how would computer science fit into its definition? Should the discipline for Computer Science be based on what programmers do, or what academics do? What kind of answers do you get from people who've seemed to think deeply about this? What reasons do they give?

答:
The discipline most accurately called "Computer Science" is, in most universities I've checked, an applied science, similar to engineering disciplines; if you major in it, you receive a "BS" or "MS". Texas Tech's CS degree was offered by the Engineering college. The discipline, as taught, is mostly theoretical; you learn the concept of Turing machines, DAs/NDAs, and other fundamental concepts that the "day-to-day" programmer doesn't really have to keep rattling around in their skull. You also get a pantload of higher math; the Texas Tech CS degree, and I'll bet many others as well, pretty much hands you a Mathematics minor to go with it. To that, most university's degree tracks add in a hefty dash of practical low-level application; you learn an assembly language, a 3rd-gen language, you explore computer graphics, operating systems, and even a good bit of electrical engineering/digital design.

However, most people who code for a living are not "computer scientists"; they are, strictly speaking, "software developers" or (when you add in analysis/design) "software engineers"; that job is much less hardware-level (though you have to know the basics of that), much more systems analysis, design and straight-out coding. Many universities have a different track just for that; at Texas Tech it was called "Management of Information Systems" and it was a Business degree (BBA/MBA). That track was lighter on higher math (what you had to know about algebra and differential/integral calc was squeezed into two semesters of "business math", and didn't include vector/tensor calc, linear algebra, etc), much heavier on financial math (a semester each of stats and finance, with two each of accounting and economics). Lighter on operating systems, heavier on "stack" technologies such as databases, web servers, networking and general systems administration. Lighter on low-level languages, circuit design and AI, heavier on 3rd and 4th-gen languages, systems analysis and project management. I got this degree from Texas Tech and by the time I'd left I'd had at least a semester each of Java, VB, C# and web languages (HTML/CSS/PHP), plus a year of OOA&D and various other courses in IT project management.

Which is better in the real world? I got the MIS BBA, my brother got the CS BS, and we're both employed at roughly the same salary level (adjusting for cost of living) as senior software engineers. He had to learn a lot of the required OOA&D on the job, as well as spin up pretty quickly in C#/Java from his basic C++ knowledge. For my part, I wish I had the two semesters of conceptual algorithm study that he got while I was stuck in business management courses (yes, MIS is a "Management" degree, but I've found that 99% of my knowledge of how to manage and not manage other people has been learned by example).