答:
This will largely depend on the MVC framework you are using. The ASP.NET MVC framework in .NET, for example, has a permissions system built in (called roles). You could use one controller with multiple methods:

public class ResourceController : Controller
{
    [Authorize(Roles = "User")]
    public ActionResult CreateAsUser()
    {
        // ...
    }

    [Authorize(Roles = "User")]
    [HttpPost]
    public ActionResult CreateAsUser(ResourceModel model)
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    public ActionResult CreateAsAdmin()
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    [HttpPost]
    public ActionResult CreateAsAdmin(ResourceModel model)
    {
        // ...
    }
}
```

Most fully featured MVC frameworks will have some kind of role based permissions system built in that you can use. Really, your next step is identifying the MVC framework you are using (or decide which one to use now that you know it needs role based permissions) and do some research on how to implement those permissions.

Title: Multiple controllers for same resource based on user's Role

Body:
I'm having trouble designing this role (or permission) based application, when it comes to figuring out how to handle actions that differ per use role.

For instance, our controller is App\ResourceController, and we will be editing the resource. There are 2 roles: admin and user. The admin is allowed to edit every field of the resource, while the user is restricted to some of them.

I'm struggling figuring out the best approach between implementing a single controller that will handle both cases, or routing the request to a different controller for the same resource (like App\Admin\ResourceController, App\User\ResourceController).

The issue with the single controller approach, is that it isn't just showing a different form (with restricted fields) based on role, but also validating different fields and more. The controller's body would pretty much look like a big if-else statement.

Is multiple controller the correct approach, or is there a different one using permissions instead of roles?

Body:
This will largely depend on the MVC framework you are using. The ASP.NET MVC framework in .NET, for example, has a permissions system built in (called roles). You could use one controller with multiple methods:

public class ResourceController : Controller
{
    [Authorize(Roles = "User")]
    public ActionResult CreateAsUser()
    {
        // ...
    }

    [Authorize(Roles = "User")]
    [HttpPost]
    public ActionResult CreateAsUser(ResourceModel model)
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    public ActionResult CreateAsAdmin()
    {
        // ...
    }

    [Authorize(Roles = "Admin")]
    [HttpPost]
    public ActionResult CreateAsAdmin(ResourceModel model)
    {
        // ...
    }
}

Most fully featured MVC frameworks will have some kind of role based permissions system built in that you can use. Really, your next step is identifying the MVC framework you are using (or decide which one to use now that you know it needs role based permissions) and do some research on how to implement those permissions.


问:
Is 4-5 years the “Midlife Crisis” for a programming career?
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

答:
I worked for 2 companies in 2 different continent with total different mentalities but what they have in common that they both don't care about programmers... Programmer is usually associated with the bottom level of companies... They are usually associated with beginners and have the smallest wages... while Project Managers, architects etc... usually take more money and do less work...

I have been working for almost 4 years now and I have nearly the same feeling as you... Switching between projects... trying all the possible programming languages... C, C#, php, ASP.NET, WinForm, C++, Python, VB.NET, VBA... and a lot more was some of the languages I worked with... Since the moment your superiors discover that you can make it with any language that they give you, they will tag you as a "good" resource and give you all the dirty job...

I haven't neither got a mentor to guide me thorough my career... and like many who wrote here... I only find my satisfaction when I do make my personal projects... but unfortunately usually the long hours of work didn't let me to make some serious work...

In conclusion, I will spend some months lost till I decide like the majority of passionate developer to give up and take a merely boring architect post to get more cash

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Zied


问:
Difference in endianness between operating systems
There is an assembler that I am writing that is located within the file asm.c located in this repository. It uses the instruction set located in the specs file to produce an output binary. (The program that would run this binary has not yet been made - the beginning is located in main.c.) Using the example program named echochar.sdmasm, the assembler outputs the desired binary. Here it is in hex:

```<code>90 00 a0 00
</code>```

But it only does this so far on a Windows machine under Cygwin. (I have not yet tested it under Linux.) On an Intel-based Mac, this is the resultant binary:

```<code>00 90 00 a0
</code>```

This looks like a difference in endianness, but I thought that this could only happen when two processors are completely different. This seems to be and endian difference between operating systems, not processors. Is this really the case, or is something else going on here that I am not getting?

Just managed to test it on Linux - the output error occurs as it does on the Mac.

Okay, something else is going on entirely. Output from hd on Linux:

```<code>00000000  00 90 00 a0                                       |....|
00000004
</code>```

Output from hexdump on Linux:

```<code>0000000 9000 a000
0000004
</code>```

This is really odd. I can't tell which one is the correct output.

答:
Something else is going on, likely a bug in the code.

It looks like an off-by-one error to me, not an endianness change.

Check your type widths and your bit shifts.

ContentLicense: CC BY-SA 3.0


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
Minimize side effects (ideally have none)

A function that causes 3 changes to states outside of its own scope is much more difficult to reason about and maintain than one just which just inputs something and outputs something else. You can't just know what the function does, you have to remember what it did and how that effects all other relevant functions.

For OOP minimizing side effects also means classes with fewer members, and especially fewer members that can modify the class's state, since member functions can modify states beyond their own and have side effects (they can manipulate the class's internals, e.g.). It also means classes with fewer data members of their own so that there's less state for those methods to tamper with and fewer side effects they can cause.

As a simple example, imagine trying to design a fancy data structure which can maintain a sorted state which it uses to determine whether to perform binary or linear searches. In such a case, it might be useful to separate the design into two classes. Calling sorted on the unsorted class might then return a data structure of another class which always keeps its contents sorted. Now you have less side effects (therefore less error-prone and easier to comprehend code) as well as more widely applicable code (the former design would be wasteful both in processing and human intellectual efficiency for small arrays that never need to be sorted).

Avoid Superfluous External Dependencies

You might be able to implement the most terse code imaginable with maximum code reuse by using 13 different libraries to accomplish a relatively simple task. However, that transfers intellectual overhead to your readers by then having to make them understand at least parts of 13 different libraries. This inherent complexity should be immediately appreciated by anyone who tried to build and comprehend a third party library which required pulling in and building a dozen other libraries to function.

This is probably a very controversial view but I would prefer some modest code duplication to the opposite extreme provided the end result is well-tested (nothing worse than untested faulty code duplicated many times over). If the choice is between 3-lines of duplicated code to compute a vector cross product or pulling in an epic math library just to shave off 3 lines of code, I'd suggest the former unless your entire team is on board with this math library, at which point you might still consider just writing 3 lines of code instead of 1 if it's trivial enough in exchange for the decoupling benefits.

Code reuse is a balancing act. Reuse too much and you transfer intellectual complexity in a one-to-many kind of way, as in those 3 lines of simple code you saved above comes at the cost of requiring the readers and maintainers to understand far more information than 3 lines of code. It also makes your code less stable, since if the math library changes, so too might your code. Reuse too little and you also multiply the intellectual overhead and your code ceases to benefit from central improvements, so it's a balancing act, but the idea that it's a balancing act is worth mentioning since trying to stamp out every little form of modest duplication can lead to a result that's as difficult to maintain, if not more, than the opposite extreme.

Test the Crap Out of It

This is a given but if your code doesn't handle all input cases and misses some edge cases, then how can you expect others to maintain code you wrote that you didn't even get right before it transferred to their eyes and hands? It's difficult enough to make changes to code that works perfectly let alone code which was never quite right in the first place.

On top of that, code that passes thorough tests is generally going to find fewer reasons to change. That relates to stability which is even more of a holy grail to achieve than maintainability, since stable code that never needs to be changed incurs no maintenance cost.

Interface Documentation

Prioritize "what things do" over "how things do them" if you can't devote equal time to documenting both. A clear interface that is obvious in its intentions about what it will do (or at the very least, what it's supposed to do) in all possible input cases will yield a clarity of context to its own implementation which will guide in understanding not only how to use the code, but also how it works.

Meanwhile code that lacks these qualities where people don't even know what it's supposed to do is SOL no matter how well-documented its implementation details are. A 20-page manual on how source code is implemented is worthless to people who can't even figure out exactly how it's supposed to be used in the first place and what it's even supposed to do in all possible scenarios.

For the implementation side, prioritize documenting what you do differently from everyone else. As an example, Intel has a bounding volume hierarchy for their raytracing kernels. Since I work in this field, I can recognize the bulk of what their code is doing at a glance without sifting through documentation. However, they do something unique which is the idea of traversing the BVH and performing intersections in parallel using ray packets. That's where I want them to prioritize their documentation because those parts of the code are exotic and unusual from most historical BVH implementations.

Readability

This part's very subjective. I don't really care that much about readability of a kind that's close to human thought processes. The most well-documented code describing things at the highest level is still difficult for me to follow if the author uses bizarre and convoluted thought processes to solve a problem. Meanwhile terse code using 2 or 3 character names can often be easier for me to understand if the logic is very straightforward. I guess you could peer review and see what other people prefer.

I'm mostly interested in maintainability and, even more importantly, stability. Code that finds no reasons to change is one that has zero maintenance costs.


答:
If you're good at what you do, as a programmer, most people you encounter in corporate life, will have more to lose than to gain. Senior management would gain from your abilities and you need to ensure you have their support.

Find your own mentor. It is your responsibility, if you love this game, to find someone to help you grow.

Title: Is 4-5 years the “Midlife Crisis” for a programming career?

Body:
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

OwnerDisplayName: wentbackward


问:
If you decide that branching is a bad thing, then why use Git over SVN?
I have used Git and Mercurial a bit over the past ten years and appreciate and prefer them, but most of my experience is with SVN.  If it is decided within a corporate programming group that branching and merging are not to be done because they cause too many problems then what significant benefit remains for Git over SVN?  I am aware that offline and local abilities are beneficial but it seems to me that their benefits are minimized by the banning of branching techniques and the minimal amount of time spent working offline.

I prefer Git and am not looking to argue against it but it has been said to me that Git would make things better even though we should not branch and merge.

答:
It's beneficial because the entire company doesn't have to use the same policy.  You can have an official no branch policy on the official central repo for the branch-averse people, but small local teams can pull from each other, commit frequently, and set their own policies, as long as they adhere to the policies when they push to the official central repo.

I actually use git on top of perforce, so I can commit locally much more frequently between perforce commits, which provides a lot of freedom to experiment, while being able to easily back out debugging changes from the last 10 minutes or so.  I can quickly create a local branch to fix a bug, then return to my long-term task.  There are a lot of benefits to using git without long-term branches, even locally without the official approval of the company.


答:
Taking the SVN model, you are going to have N+1 branches for every N developers modifying the head branch. This gets more complicated once you factor that eventually these branches do not share the same common ancestor (i.e. modification was started from a different commit).

So, even if you only publish a single branch, your tool must support merging and conflicts. Git lets you support branches with a model that handles these simple cases, plus things much more complicated. The benefit for the user is that once you understand this model, it can be applied to the complex actions while keeping the fundamental process the same.

For example, you could create an unlimited number of branches in your local repo that can be merged, modified, re-ordered, adjusted, etc. The commands for handling these operations are the same as if you were working with branches created by others.

Assume though, that your project is just 1 developer who always commits to the master branch (i.e. there is truly a single branch), the architecture of git is far superior to SVN in a number of fundamental ways.

The SHA1 hash of your branch validates the integrity of the entire branch. If any file or commit message is modified, the SHA1 value would change. This guarantees that you will immediately detect corruption of your repo data.

The git repo is self-contain and does not require a server or any configuration. You literally can create a new repo in under 1 second.

Git keeps all your revisions in your local repo. This makes running search and diff commands between changes orders of magnitudes faster than SVN. Imagine finding the commit that changed a line out of 10,000 changes, or finding any change that contained a global variable in code base with 50,000 files or more. Git can return results in seconds when running on ubiquitous SDD drives.

Git tracks content not files. This gives it amazing abilities to easily track files that were renamed or blocks of code that moves between files. Some tools like SVN support renames, but git does this without you having to tell it there was a rename.

Git makes it easier to create a commit that implements a "single logical change". This is important for reading your commit history and when you need to revert specific commits that were later found to either need additional work or become obsolete. SVN will only let you submit a single file at a time, but coding doesn't always happen linearly and sometimes if you forget to submit each change, you'll eventually collect 3 or 4 separate changes in the same file. Git makes it easy to create 4 commits from 4 changes in the same file (however if the changes overlap, you still have to recreate the intermediate states that were lost)

Title: If you decide that branching is a bad thing, then why use Git over SVN?

Body:
I have used Git and Mercurial a bit over the past ten years and appreciate and prefer them, but most of my experience is with SVN.  If it is decided within a corporate programming group that branching and merging are not to be done because they cause too many problems then what significant benefit remains for Git over SVN?  I am aware that offline and local abilities are beneficial but it seems to me that their benefits are minimized by the banning of branching techniques and the minimal amount of time spent working offline.

I prefer Git and am not looking to argue against it but it has been said to me that Git would make things better even though we should not branch and merge.


问:
What technique can I use to test my code when code renders out an untestable(?) PDF document?
I have a need to test output of my code before I send the output for PDF rendering.

Currently I have decided on a switch statement that does two different things depending on whether I am in production or in testing mode.

Render PDF with data that goes on PDF in a web browser.  Nothing is returned to caller

Do not render the PDF but just return the data for test/other purposes

Just to show some code to clarify ...  Here is what I have now:

```<code>$output = $this->prepOutputData();
switch ($this->strategy)
{
    //outputs binary PDF, no return statement
    case OutlineStrategy::PDF_STRATEGY:
        $pdfEngine = new PdfEngine();

        $em = DoctrineConnector::getEntityManager();
        $metaData = $em->getRepository(PdfMetadata::class)->findAll();

        $pdfEngine->arrangeDataOnPdf($metaData, $output);
        $pdfEngine->printPdfToBrowser();
        break;

    //returns data that goes onto PDF
    //for testing or for consumption by non-PDF entity
    case OutlineStrategy::TEST_STRATEGY:
        return $output;
        break;
}
</code>```

Goal

My goal is to be able to show PDF in production but NOT show PDF for testing and yet to be able to run test checks on the $output data.  How can I do that?

答:
I removed strategy constructs (OutlineStrategy::PDF_STRATEGY, etc) out of my code.  Then rewrote code to use services.

I will test services and not the PDF generation.  aka PDF Generation will be untested, but the processes leading up to it will be tested.

Per Doc Brown wrote a function just for testing output.

```<code>public function generateOutline($input)
{
    $output = $this->getOutput($input);
    $this->pdfService->renderPdf($output);
}

public function testOutput($input)
{
    return $this->getOutput($input);
}

private function getOutput($input)
{
    $data = $this->inputFilter->getOutlineRequestData($input);
    $output = $this->processor->processInput($data);
    return $output;
}
</code>```

Notice public/private modifiers

Body:
I removed strategy constructs (OutlineStrategy::PDF_STRATEGY, etc) out of my code.  Then rewrote code to use services.

I will test services and not the PDF generation.  aka PDF Generation will be untested, but the processes leading up to it will be tested.

Per Doc Brown wrote a function just for testing output.

public function generateOutline($input)
{
    $output = $this->getOutput($input);
    $this->pdfService->renderPdf($output);
}

public function testOutput($input)
{
    return $this->getOutput($input);
}

private function getOutput($input)
{
    $data = $this->inputFilter->getOutlineRequestData($input);
    $output = $this->processor->processInput($data);
    return $output;
}

Notice public/private modifiers


问:
Is having only static pages calling the backend a good idea?
I'm new to web applications development, specially when it comes to frontend, but as I understood, a typical structure for a big application would have a frontend php (or equivalent) layer calling the backend services and generating dynamic pages.

Now we're building a new site, and a colleague of mine insists on not having the layer that generates the dynamic pages. He wants the pages to be mere skeletons with html and JS, so basically static web pages, and directly invoking the backend (REST) with JS. This, of course, means having the backend services publicly available, which I'm not particularly comfortable with.

Is this architecture approach advisable? Does it scale?

答:
That architecture your colleague suggested is pretty common nowadays - it's called Single Page Application.

In terms of security the two methods are equivalent - in both cases the server is generating all data required for creating the page, and sending it to the client. The only difference is where and how this data gets formatted into to form displayed to the user.

For example, if you want to allow the user the search for products, in the classic approach the server will generate the entire HTML page with the list of products in it, and in the SPA approach the server will generate the same list of products, but instead of rendering HTML it'll serialize the list into XML or JSON or whatever other format and send the serialized list to the client.

Notice that in both cases:

All the data required to display the products is transferred on the wire.

Data not needed for displaying the products or for performing farther operations on them(like the product ID that even if you don't display it the client still need it in case the user clicks on the button for ordering the product) does not reach the client.

The internal services are not publicly available - you can't query the DB directly even with SPA, only to invoke the method that generates the list of products(and any other method you decide to expose to the client - but you would have to expose similar services in the classic approach as well)

Security-wise, the only advantage of the classic approach over the SPA approach is that SPAs make it a bit easier to programmatically use your application - for example it's easier for me to create a script that runs every morning, logs in with my credentials, requests the list of products, and emails me if you've added a new product. But I could have done it with the classic approach as well - it would have been a little harder(because it's harder to extract the data from HTML page than from a serialization format) but it would have still been possible(I've actually done that a few times...)


问:
Updating particular properties of EF objects every X amount of days in MVC
I'm building an MVC ASP.NET IMDb-like website which presents various information about movies to users, relying on 3rd party APIs to (initially) fetch movie info.

The IDs representing each movie on the website are identical to IMDb's (ID tt1234567 points to the same movie on both websites).

The way movie info are fetched (and subsequently stored on SQL server) is as follows:

User requests movie with id tt1234567

MVC checks if movie with id tt1234567 exists in the database.

If not, it queries external APIs to fetch movie information and stores it in the database.

If yes, it fetches the information directly from the database.

This works fine and I'm at the point where I'm implementing caching. There are some particular columns for each row in the Movie table which change every certain amount of days (e.g. overall rating and number of votes for that movie in IMDb). As such, I need to implement a function where relevant columns of the row are updated after certain amount of time (e.g. every 10 days).

What would be the correct approach to do this? Should I implement a scheduled task which runs every 10 days and updates the needed columns in the DB, or should I somehow add caching into the mix?

答:
I think that Ewan's advice is ok. 10 days is a long period of time, especially when your database grows to tens of thousands or more movies. Things to be considered when implementing the solution:

if your web app is used less in some period of the day (based on logs), try to use that period for async operations like this (this is particularly useful when inserts or updates volume is high and tables are locked for a larger period of time)

synchronous check since is also a solution, but pay attention to the extra delay for the client (time to fetch data from IMDB, parse, update in db). Based on discussion from here, it should not be a problem, though

I would favor the async option, since you have better control over how often you query IMDB (I expect to have some limitations to avoid abuse). Theoretically, if someone or a bot is crawling your site and you use the sync option, you might run into lots of fetches from IMDB.


问:
Design pattern for mapping data fields
I have seen this problem a few times and never can come up with a solution i like.

```<code>System A
    Sales Order Entity
        order_id
        created
        line_items_count

System B
    Sales Order Entity
        sales_order_id
        created_At
        num_line_items
</code>```

The problem is, that sales orders are created in System A - for example an e-commerce website.  The sales orders need to be exported and stored in another system, for example a warehouse system - System B.  They both store the same data but under different field names.

Is there a design pattern or collection of patterns typically used to solve such problem?

I always end up with an associative array containing the mapped fields - but it feels like there must be a better solution.

In the example above, not only sales orders might require this, also customers, products, inventory levels etc - so a generic pattern would be best.

答:
Though probably not recognised as a design pattern, what you describe would be called a Mapper.

It translates one object into another.

Implementations can be found at AutoMapper.org and at CodeProject.

Title: Design pattern for mapping data fields


答:
Somehow we have a similar feeling. Now I am wondering if this is happening because we're both having five years of experience or because of the organized rising of those people who read "Clean Code" (we in germany have a quite active community around the "Clean Code Devloper" initiative) , "Pragmatic Programmer" and "Code Complete" like ALT.NET and so on. All the blogs are full of ideas how to do things right and clean.

So I am thinking, that the five years of experience is just a matter of coincidence, while the main reason is the change of the industry - which is quite new: houses and bridges are being build since thousands of years, machines are constructed for many hindrets of years, higher medical stuff goes hundred years, computers some 50 years and we're coding in a 3rd generation language since 20 years. See the point? It takes time to become mature for an industry, and I think the industry is coming to the age of adolescence :-)

OwnerDisplayName: Marc Wittke


问:
.NET DataSource binding for legacy SQL Server DB with undefined relationships
I'm designing a utility that will load data into a legacy SQL Server Database.

I've been trying to mock up a simple WinForms utility with C# using the DataSource connectors (Tried a straight ORM Entity Framework approach first, but was having problems as the db follows few conventions).

I am having particular difficulty in establishing parent/child relationships and displaying them with data grids (ie, click on this row and the child grid gets filtered).

Some examples of database challenges:

No foreign keys with referential constraints.  What would normally be a foreign key shows up as part of the Primary composite key in "child" table.  Sometimes with different data types (ie, double instead of long)

Sometimes a composite key is used on a parent table to define the entity, but only one of those composite fields shows up in a "child" table. {dbo.Parent Key = [ParentID, ParentGroupID, OtherField], dbo.Child Key = [ChildID, ParentID]}

Naming conventions are non existent.

Things like this make it difficult to bind data sets to parent/child data grids, and use some of the other out of the box functionality that .NET offers.

How to address above challenges?

I tried looking at some older ADO.Net tutorials but sometimes methods have changed or are no longer available...

答:
The tutorial suggested by wesmantooth seems just fine, but I am thinking about something more convoluted. If you have the available time and this application is going to live at least for a few years from now, you can try the following (at least partially):

for each legacy table define a new table (place it in a new schema) that holds the same information, but has decent column names and all the appropriate constraints

new tables can have all the appropriate foreign keys to ensure integrity and also get navigation properties (EF)

whenever you persist some data, you easily save in your new tables and call a stored procedure to update data in the old structure - I think that MERGE is your best friend here.

The main advantages are: you work with decent data structures in your .NET code, have easier data fetch and data persistent logic and you open the perspective of getting rid of ugly legacy data structure in some point in future.

The main disadvantage is the great effort put into doing this. I would start with those tables that are less used in reports, ETL etc.


答:
Given your expected output as shown above (i.e. 90 00 etc), your code is incorrect - it assumes it is running on a big-endian machine.  I would suggest either changing your fwrite to a couple of fputc calls, or alternatively assembling your instructions byte-by-byte in an array of uint8_t.

As to the discrepancies of output, it seems some of the viewer programs you are using are reading 16-bit words in little-endian mode and others are reading byte-by-byte, thus the discrepancy. This is made more confusing by the fact that your output is not what you expect, probably causing you to look in the wrong place for the issue.

Title: Difference in endianness between operating systems

Body:
There is an assembler that I am writing that is located within the file asm.c located in this repository. It uses the instruction set located in the specs file to produce an output binary. (The program that would run this binary has not yet been made - the beginning is located in main.c.) Using the example program named echochar.sdmasm, the assembler outputs the desired binary. Here it is in hex:

```<code>90 00 a0 00
</code>```

But it only does this so far on a Windows machine under Cygwin. (I have not yet tested it under Linux.) On an Intel-based Mac, this is the resultant binary:

```<code>00 90 00 a0
</code>```

This looks like a difference in endianness, but I thought that this could only happen when two processors are completely different. This seems to be and endian difference between operating systems, not processors. Is this really the case, or is something else going on here that I am not getting?

Just managed to test it on Linux - the output error occurs as it does on the Mac.

Okay, something else is going on entirely. Output from hd on Linux:

```<code>00000000  00 90 00 a0                                       |....|
00000004
</code>```

Output from hexdump on Linux:

```<code>0000000 9000 a000
0000004
</code>```

This is really odd. I can't tell which one is the correct output.


问:
What is the best approach to compare data in a database?
I am going to ask some random questions from hundreds of them to my users and the answers can be only "true" or "false". Then I am going to record those answers into my database and lastly I am going to compare those answers and find relations between them such as "User A" and "User B" have 20 answers in common and notify those users.

New users can join the service or actual users can answer more questions in time, so I need to do make comparison frequently.

What is the best business logic or approach to proceed?
How can I do this in a scalable way?
How can I google solutions or tutorials for this question (any keyword)?

This is how my database looks like for this process:

I have three tables in my database:

One of them called "users" and keeps the information of the registered
users such as username, password, etc.

Second one called "questions" and keeps the questions to be asked to users.

(Two columns; question id and question text)

Last one called "answers" and keeps the answers given by the users.

(Two columns; question id and answer (TRUE/FALSE))

答:
The following query:

```<code>SELECT a.user_id AS a_user_id,
       b.user_id AS b.user_id,
       a.question_id,
       a.answer
FROM
    answers AS a INNER JOIN answers AS b
        ON a.question_id = b.question_id AND a.answer = b.answer;
WHERE
    a.user_id <> b.user_id;
</code>```

will give you a long, long table with all identical answers by all users.
You could then process this table to find the answers that your users have in common, or you could use COUNT() and GROUP BY to get only counts.

Try this first; make some money while your users number in the thousands and not in the millions;  if this does not perform well enough by the time your users will be numbering in the millions, you will already be a millionaire, so you will be able to afford a team of Ph.Ds to work on the problem and provide a more optimal, more scalable solution.

Body:
The following query:

SELECT a.user_id AS a_user_id,
       b.user_id AS b.user_id,
       a.question_id,
       a.answer
FROM
    answers AS a INNER JOIN answers AS b
        ON a.question_id = b.question_id AND a.answer = b.answer;
WHERE
    a.user_id <> b.user_id;

will give you a long, long table with all identical answers by all users.
You could then process this table to find the answers that your users have in common, or you could use COUNT() and GROUP BY to get only counts.

Try this first; make some money while your users number in the thousands and not in the millions;  if this does not perform well enough by the time your users will be numbering in the millions, you will already be a millionaire, so you will be able to afford a team of Ph.Ds to work on the problem and provide a more optimal, more scalable solution.


问:
Explanation to why Counting bits set, Brian Kernighan's way works
I found this link to count number of bits in a variable. I think it is pretty cool, but I can't figure out why it works. Can someone offer an explanation?

Here is the code

```<code>unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}
</code>```

Any help is appreciated.

答:
The idea is that each iteration sets the least significance bit that isn't zero to zero -and only it. Since each iteration converts exactly bit from 1 to 0, it'll take as many iterations as there are non-0 bits to convert all the bits to 0(and thus v == 0 and the loop finishes).

So, how does this work? Lets say that the bit at index n is 1 and that the bits in indexes 0 upto n-1 are all 0(we'll use little endianess - so index 0 is 1, index 1 is 2, index 2 is 4, index 3 is 8 and so on).

v-1 subtracts from index 0 - but it's 0, so it converts it to 1 and subtracts from index 1 - but it's also 0, so it converts it to 1 and subtracts from index 2 - and so on until we reach index n. Since index n is 1 it can subtract from it and turn it to 0 - and there it stops.

So, v-1 is like v except there are n 0 that became 1 and one 1 that became 0. In v & v - 1 all the other bits remain as is, the n zeros that where turned to ones remain 0(because 0 & 1 == 0), and the one 1 that was turned to 0 turns to 0(because 1 & 0 == 0). So overall - only a single bit was changed in the iteration, and this change was from 1 to 0.


答:
From my experience also in some large companies the situation is the same. What matters is the organization's values and policies and much less its size.

Try finding a sub-field of software engineering that you are more passionate about and enquiring what companies have jobs in the field and what working there is like.

The seniors are usually people that either have been there for a long time, or have key positions (e.g. team leaders, architects, ...), however staying in one company for a long time tends to have a negative influence, since you get used to the situation their and the technologies they use and you strive less to change things and try new approaches. - Fresh minds are very important, internal experience is important for knowing how to get things done in that company, companies should have a combination of both.

Also try to get your work place to send you to as many external courses as possible, that you think will improve your technical knowledge and working methods.

OwnerDisplayName: Danny Varod


问:
What is the exact ingenuity of Unix pipe
I have heard the story of how Douglas Mcllroy came up with the concept and how Ken Thompson implemented it in one night.

As far as I understand, pipe is a system call which shares a piece of memory between two processes where one process writes and other reads from.

As someone who is not a familiar with OS internals or concepts, I was wondering what exactly is the "genius" in the story?
Is it the idea of two processes sharing memory? Or is it the implementation? Or both?

PS: I am aware of the utility of the pipe or how to use it in shell. The question is about concept and implementation of the |

答:
In my opinion, the genius of the idea of "pipes" is the simplicity of use.

You don't have to make any system calls, allocate memory, nothing complicated at all.  In the shell, you use a single character: |.  This gives extraordinary power in the combination of simple (or complex) tools to a given task.

Take some common everyday tasks like sorting text neatly.  You may have a command that lists a whole bunch of names.  (For my example I'll use a file that contains a bunch of names, courtesy of listofrandomnames.com.)  Using pipes you can do something like the following:

```<code>$ cat names.txt
Sally Weikel
Dana Penaflor
Christine Hook
Shaneka Flythe
Almeda Crook
Freddie Lindley
Hester Kersh
Wanda Ruse
Megan Mauzy
Samuel Mancha
Paris Phipps
Annika Accardo
Elena Nabors
Caroline Foti
Jude Nesby
Chase Gordy
Carmela Driggers
Marlin Ostendorf
Harrison Dauber
$ cat names.txt | awk '{print $2 ", " $1}' | sort | uniq | column -c 100
Accardo, Annika     Hook, Christine     Ostendorf, Marlin
Crook, Almeda       Kersh, Hester       Penaflor, Dana
Dauber, Harrison    Lindley, Freddie    Phipps, Paris
Driggers, Carmela   Mancha, Samuel      Ruse, Wanda
Flythe, Shaneka     Mauzy, Megan        Weikel, Sally
Foti, Caroline      Nabors, Elena
Gordy, Chase        Nesby, Jude
</code>```

This is just one example; there are thousands.  For a few other specific tasks that are made remarkably easier by use of pipes, see the section "The Unix Philosophy" on this page.

To underscore this answer, see slides 4 through 9 of the presentation, "Why Zsh is Cooler than Your Shell."

I am aware that the above command includes a UUOC.  I let it stand because it is a placeholder for an arbitrary command that generates text.

Body:
In my opinion, the genius of the idea of "pipes" is the simplicity of use.

You don't have to make any system calls, allocate memory, nothing complicated at all.  In the shell, you use a single character: |.  This gives extraordinary power in the combination of simple (or complex) tools to a given task.

Take some common everyday tasks like sorting text neatly.  You may have a command that lists a whole bunch of names.  (For my example I'll use a file that contains a bunch of names, courtesy of listofrandomnames.com.)  Using pipes you can do something like the following:

$ cat names.txt
Sally Weikel
Dana Penaflor
Christine Hook
Shaneka Flythe
Almeda Crook
Freddie Lindley
Hester Kersh
Wanda Ruse
Megan Mauzy
Samuel Mancha
Paris Phipps
Annika Accardo
Elena Nabors
Caroline Foti
Jude Nesby
Chase Gordy
Carmela Driggers
Marlin Ostendorf
Harrison Dauber
$ cat names.txt | awk '{print $2 ", " $1}' | sort | uniq | column -c 100
Accardo, Annika     Hook, Christine     Ostendorf, Marlin
Crook, Almeda       Kersh, Hester       Penaflor, Dana
Dauber, Harrison    Lindley, Freddie    Phipps, Paris
Driggers, Carmela   Mancha, Samuel      Ruse, Wanda
Flythe, Shaneka     Mauzy, Megan        Weikel, Sally
Foti, Caroline      Nabors, Elena
Gordy, Chase        Nesby, Jude

This is just one example; there are thousands.  For a few other specific tasks that are made remarkably easier by use of pipes, see the section "The Unix Philosophy" on this page.

To underscore this answer, see slides 4 through 9 of the presentation, "Why Zsh is Cooler than Your Shell."

I am aware that the above command includes a UUOC.  I let it stand because it is a placeholder for an arbitrary command that generates text.

ContentLicense: CC BY-SA 4.0


答:
As far as I understand, pipe is a system call which shares a piece of memory between two processes where one process writes and other reads from.

Actually, there is no shared memory involved.  The reader and writer are NOT sharing any part of their address space, and they are not using any explicit synchronization.

The reading and writing processes are making read and write system calls exactly as they would if they were reading from / writing to a file.  THAT is the genius... the innovation: the notion that (simple) interprocess communication and file I/O can be handled the same way... from the perspective of the application programmer and the user.

Once the pipe has been set up, the OS (not application code, or libraries in user-space) takes care of the buffering and the coordination.  Transparently.

By contrast, before the invention of the pipe concept, if you needed to do "pipeline" processing, you would typically have one application write output to a file, and then when it is finished, you would run the second application to read from the file.

Alternatively, if you wanted a true pipeline you could code both applications to set up a (real) shared memory segment and use semaphores (or something) to coordinate the reading / writing.  Complicated... and as a consequence not often done.

Title: What is the exact ingenuity of Unix pipe

Body:
I have heard the story of how Douglas Mcllroy came up with the concept and how Ken Thompson implemented it in one night.

As far as I understand, pipe is a system call which shares a piece of memory between two processes where one process writes and other reads from.

As someone who is not a familiar with OS internals or concepts, I was wondering what exactly is the "genius" in the story?
Is it the idea of two processes sharing memory? Or is it the implementation? Or both?

PS: I am aware of the utility of the pipe or how to use it in shell. The question is about concept and implementation of the |


问:
How to "program to an interface"
I've read these questions:

Understanding "programming to an interface"

What is the point of an interface?

Does it always make sense to "program to an interface" in Java?

I don't understand how to "program to an interface" if you are using methods in concrete classes that aren't part of the interface.

I realize the most common example of this design principle is the List vs ArrayList in Java because it is easy to understand and illustrate the point.

Here is a somewhat silly example to illustrate what my question is asking (the code is in PHP but it applies to most OOP languages):

interface ResponseInterface {
    public function getStatusCode();
}

class Response implements ResponseInterface {
    private $status;

    public function getStatusCode() {
        return $this->status;
    }
}

class AwesomeResponse implements ResponseInterface {
    private $status;
    private $message = ['200' => 'OK', '500' => 'Internal Server Error'];

    public function getStatusCode() {
        return $this->status;
    }

    public function getStatusMessage() {
        return $this->message[$status];
    }
}

class Server {
    public function sendResponse(ResponseInterface $response) {
        // this seems wrong -----^

        header(vsprintf('HTTP/1.1 %d %s', [
            $response->getStatusCode(),
            $response->getStatusMessage()
        ]), true, $response->getStatusCode());
    }
}
```

<p>As you can see, the <code>sendResponse</code> method takes a <code>ResponseInterface</code> parameter but it calls <code>getStatusMessage()</code> which isn't part of the interface but only something implemented in <code>AwesomeResponse</code>, which implements <code>ResponseInterface</code>.</p>

<p>The application crashes at runtime when a <code>Response</code> object is passed as it tries to call the non-existent method <code>getStatusMessage()</code>. Therefore, the proper implementation would be:</p>

<pre class="lang-php prettyprint-override"><code>public function sendResponse(AwesomeResponse $response) {
    // ...stuff
}
</code>```

But AwesomeResponse isn't an interface so how do I program to an interface?

答:
That is the point. If you depend on concrete details of the class, you are not coding to an interface by definition.

This means you cannot drop out those implementation details and replace them with others. Since change is inevitable in business, this is going to cause you problems down the road. You will need to add that capability to the interface (or make another interface for that other functionality) and work with that contract, not the details that you happen to be using now.

Title: How to "program to an interface"


答:
Hmm - a less trivial example might help.  Consider Executor, which is an interface that defines a contract for executing Runnables.

Now, if you write AwesomeService like this:

```<code>class AwesomeService {
    // ...
    public void runAllPendingTasks(ScheduledThreadPoolExecutor executor) {
        for(Runnable task : pendingTasks) {
            executor.execute(task);
        }
    }
 }
</code>```

Then my code, trying to call yours, needs to find a ScheduledThreadPoolExecutor lying around somewhere.  On the other hand, if your method signature admits that your needs can be satisfied by anything that implements Executor

```<code>class AwesomeService {
    // ...
    public void runAllPendingTasks(Executor executor) {
        for(Runnable task : pendingTasks) {
            executor.execute(task);
        }
    }
 }
</code>```

The my code can pass you my customized Executor, and there by enhance what actually happens when you run your tasks.  For instance, I might want to track how often we run tasks, so that I can generate metrics in real time that monitor the health of the application.

```<code>class MeteredExecutor implements Executor {
    private final Executor impl;
    private final io.dropwizard.metrics.Meter meter;

    MeteredExecutor(...) {...}

    public void execute(Runnable command) {
        meter.mark();
        impl.execute(command);
    }
}
</code>```

OK, so why doesn't an interface seem to help for AwesomeResponse?  The primary answer is encapsulation -- the MeteredExecutor provides the execute service by using its own internal state to satisfy a request.  What it doesn't do is share that internal state.  Notice that AwesomeService calls execute, and lets the MeteredExecutor do the work, rather than calling getMeter().mark() and getImpl.execute(command).

"Give me your internal state" is a really lousy motivation for an interface.

AwesomeResponse is exposing its data.  That's not necessarily a bad thing; in your example as written, AwesomeResponse is essentially a representation of a message that is about to cross an application boundary.  Put another way, it's a value type that makes up part of the api of your Service; of course it exposes its data, that's what it is for!

Calling out the same point a different way: notice that in the case of AwesomeService and the interfaces, state is being passed inwards.  My state is an executor, and I pass that to AwesomeService.  The state of AwesomeService is a task, an it passes that task to the Executor, which in turn passes it inward to another Executor, and turtles all the way down.  Interfaces work great for this.

On the other hand, in AwesomeResponse, the state is coming out.  Writing interfaces to fetch the state out is just extra work.

BUT

Encapsulation is a good thing, and AwesomeResponse isn't quite at the application boundary.  Could we rewrite things so that state is passed inward?

```<code>interface Writer {
    void header(int code, String message);
}

interface Response {
    void writeTo(Writer writer);
}

class AwesomeResponse implements Response {
    void writeTo(Writer writer) {
        writer.header(this.code, this.message);
    }
}

class NotSoAwesomeResponse implements Response {
    void writeTo(Writer writer) {
        writer.header(this.code, String.valueOf(this.code));
    }
}

class ServerWriter implements Writer {
    void header(int code, String message) {
        header(vsprintf('HTTP/1.1 %d %s', [
            code,
            message
        ]), true, code);
    }
}

class Server {
    public function sendResponse(Response response) {
        ServerWriter writer = new ServerWriter();
        response.writeTo(writer);
    }
}
</code>```

Title: How to "program to an interface"

Body:
I've read these questions:

Understanding "programming to an interface"

What is the point of an interface?

Does it always make sense to "program to an interface" in Java?

I don't understand how to "program to an interface" if you are using methods in concrete classes that aren't part of the interface.

I realize the most common example of this design principle is the List vs ArrayList in Java because it is easy to understand and illustrate the point.

Here is a somewhat silly example to illustrate what my question is asking (the code is in PHP but it applies to most OOP languages):

interface ResponseInterface {
    public function getStatusCode();
}

class Response implements ResponseInterface {
    private $status;

    public function getStatusCode() {
        return $this->status;
    }
}

class AwesomeResponse implements ResponseInterface {
    private $status;
    private $message = ['200' => 'OK', '500' => 'Internal Server Error'];

    public function getStatusCode() {
        return $this->status;
    }

    public function getStatusMessage() {
        return $this->message[$status];
    }
}

class Server {
    public function sendResponse(ResponseInterface $response) {
        // this seems wrong -----^

        header(vsprintf('HTTP/1.1 %d %s', [
            $response->getStatusCode(),
            $response->getStatusMessage()
        ]), true, $response->getStatusCode());
    }
}
```

<p>As you can see, the <code>sendResponse</code> method takes a <code>ResponseInterface</code> parameter but it calls <code>getStatusMessage()</code> which isn't part of the interface but only something implemented in <code>AwesomeResponse</code>, which implements <code>ResponseInterface</code>.</p>

<p>The application crashes at runtime when a <code>Response</code> object is passed as it tries to call the non-existent method <code>getStatusMessage()</code>. Therefore, the proper implementation would be:</p>

<pre class="lang-php prettyprint-override"><code>public function sendResponse(AwesomeResponse $response) {
    // ...stuff
}
</code>```

But AwesomeResponse isn't an interface so how do I program to an interface?

Body:
Hmm - a less trivial example might help.  Consider Executor, which is an interface that defines a contract for executing Runnables.

Now, if you write AwesomeService like this:

class AwesomeService {
    // ...
    public void runAllPendingTasks(ScheduledThreadPoolExecutor executor) {
        for(Runnable task : pendingTasks) {
            executor.execute(task);
        }
    }
 }

Then my code, trying to call yours, needs to find a ScheduledThreadPoolExecutor lying around somewhere.  On the other hand, if your method signature admits that your needs can be satisfied by anything that implements Executor

class AwesomeService {
    // ...
    public void runAllPendingTasks(Executor executor) {
        for(Runnable task : pendingTasks) {
            executor.execute(task);
        }
    }
 }

The my code can pass you my customized Executor, and there by enhance what actually happens when you run your tasks.  For instance, I might want to track how often we run tasks, so that I can generate metrics in real time that monitor the health of the application.

class MeteredExecutor implements Executor {
    private final Executor impl;
    private final io.dropwizard.metrics.Meter meter;

    MeteredExecutor(...) {...}

    public void execute(Runnable command) {
        meter.mark();
        impl.execute(command);
    }
}

OK, so why doesn't an interface seem to help for AwesomeResponse?  The primary answer is encapsulation -- the MeteredExecutor provides the execute service by using its own internal state to satisfy a request.  What it doesn't do is share that internal state.  Notice that AwesomeService calls execute, and lets the MeteredExecutor do the work, rather than calling getMeter().mark() and getImpl.execute(command).

"Give me your internal state" is a really lousy motivation for an interface.

AwesomeResponse is exposing its data.  That's not necessarily a bad thing; in your example as written, AwesomeResponse is essentially a representation of a message that is about to cross an application boundary.  Put another way, it's a value type that makes up part of the api of your Service; of course it exposes its data, that's what it is for!

Calling out the same point a different way: notice that in the case of AwesomeService and the interfaces, state is being passed inwards.  My state is an executor, and I pass that to AwesomeService.  The state of AwesomeService is a task, an it passes that task to the Executor, which in turn passes it inward to another Executor, and turtles all the way down.  Interfaces work great for this.

On the other hand, in AwesomeResponse, the state is coming out.  Writing interfaces to fetch the state out is just extra work.

BUT

Encapsulation is a good thing, and AwesomeResponse isn't quite at the application boundary.  Could we rewrite things so that state is passed inward?

interface Writer {
    void header(int code, String message);
}

interface Response {
    void writeTo(Writer writer);
}

class AwesomeResponse implements Response {
    void writeTo(Writer writer) {
        writer.header(this.code, this.message);
    }
}

class NotSoAwesomeResponse implements Response {
    void writeTo(Writer writer) {
        writer.header(this.code, String.valueOf(this.code));
    }
}

class ServerWriter implements Writer {
    void header(int code, String message) {
        header(vsprintf('HTTP/1.1 %d %s', [
            code,
            message
        ]), true, code);
    }
}

class Server {
    public function sendResponse(Response response) {
        ServerWriter writer = new ServerWriter();
        response.writeTo(writer);
    }
}


问:
Is it reasonable to not write unit tests because they tend to get commented out later or because integration tests are more valuable?
I was discussing unit/integration testing with a colleague, and he made an interesting case against writing unit tests. I'm a big unit test (JUnit primarily) proponent, but am interested to hear others' takes, as he made some interesting points.

To sum up his points:

When major code changes occur (new set of POJOs, major application
refactoring, etc.), unit tests tend to be commented out rather than
reworked.

Time is better spent on integration tests covering use    cases,
which make the smaller-scoped tests less/not-at-all important.

Thoughts on this? I'm still pro-unit test (as I consistently see it producing improved code), although integration tests sound at least as valuable.

答:
I don't know that I accept your colleague's arguments.

If unit tests are commented out, it's because someone's being lazy. That's not the unit tests' fault. And if you start using lazy as an excuse, you can argue against almost any practice that requires a little effort.

If you're doing it right, unit tests don't have to take a long time. They're not stopping you from doing more important work. If we all agree that fixing broken code is more important than anything else, a unit test is pretty damn important. It's an easy way to test post conditions. Without it, how do you know you've met the post condition guarantees? And if you haven't, your code is broken.

There are other, more compelling arguments against unit tests. Well, not exactly against them. Start with DHH's Test-induced design damage. He's a fun writer, so do read it. What I took from it:

If you make big design changes to accommodate your unit tests, they may hinder other goals in your project. If possible, ask an impartial person which approach is easier to follow. If your highly-testable code is hard to understand, you might lose all of the benefits you gained from unit testing. The cognitive overhead of too much abstraction slows you down and makes leaky mistakes easier. Don't discount it.

If you want to get nuanced and philosophical, there are many great resources:

Ian Bicking's Testing considered harmful (Testing isn't enough. Tests don't make code beautiful.)

Dan Manges's Increasing Code Coverage May Be Harmful (Using code coverage as a metric doesn't tell you if you're doing anything useful.)

Then there's Any good arguments for not writing unit tests? [closed] from Stack Overflow. (Overconfidence, the cost is not recognized, doesn't find the insidious bugs, not a replacement for beautiful code [kinda like Bicking], etc...)


答:
When major code changes occur, unit tests tend to be commented out rather than reworked.

With an undisciplined bunch of cowboy coders who think all tests getting "green" is fulfilled when you comment all existing tests out: of course. Reworking unit tests takes the same amount of discipline as writing them at the first hand, so what you have to work on here is your team's "definition of done".

Time is better spent on integration tests covering use cases which make the smaller-scoped tests less/not-at-all important.

That is neither completely wrong nor completely right. The effort for writing useful integration tests depends very much on what kind of software you are writing. If you have a software where integration tests can almost as easily be written as unit tests, they run still fast and give you a good coverage of your code, then your colleague has a point. But for lots of systems I have seen these three points cannot easily be fulfilled by integration tests, that's why you should strive to have also unit tests.

Title: Is it reasonable to not write unit tests because they tend to get commented out later or because integration tests are more valuable?

Body:
I was discussing unit/integration testing with a colleague, and he made an interesting case against writing unit tests. I'm a big unit test (JUnit primarily) proponent, but am interested to hear others' takes, as he made some interesting points.

To sum up his points:

When major code changes occur (new set of POJOs, major application
refactoring, etc.), unit tests tend to be commented out rather than
reworked.

Time is better spent on integration tests covering use    cases,
which make the smaller-scoped tests less/not-at-all important.

Thoughts on this? I'm still pro-unit test (as I consistently see it producing improved code), although integration tests sound at least as valuable.


答:
The reality is that length of experience doesn't really amount to any sort of guarantee when it comes to competence. A good model of what happens is the Dreyfus model of skill acquisition which although originally popularised in nursing has had a bit of a revival in software engineering - here's an example applied to Ruby (personally I'm a bit dubious about the mapping, but still an interesting read).

Sadly most people never pull themselves past the "advanced beginner" stage in their skills (note that the model should be applied per skill not to a person as a whole) - you'll only get better by not only practicing self improvement but by choosing the right sort of learning which will pull you to the next stage. This is why some people can do lots of courses, pass exams and still be rubbish.

It sounds like that you've reached a particular stage in your skill development (competent or proficient) and so are able to differentiate yourself better from others. The general pattern is that it takes 10 years to become fully expert in any particular non-trivial skill - but most people never do.

OwnerDisplayName: FinnNk


问:
What makes a language Turing-complete?
What is the minimal set of language features/structures that make it Turing-complete?</p>

答:
You can't tell if it'll loop infinitely or stop.

-------------

Explanation : Given some input, it's impossible to tell in every case (using another Turing machine) if the thing is going to loop infinitely or eventually going to stop, except by running it (which gives you an answer if it does stop, but not if it loops!).

This means that you have to be able to store a potentially unlimited amount data in some way - there has to be an equivalent to the infinite tape, no matter how convoluted! (Otherwise there are only a finite number of states and then you can check if you've been through that state previously and eventually stop). Generally, Turing machines can grow or shrink the size of their state by some controllable means.

Since Turing's original universal Turing machine has an unsolvable halting problem, your own Turing complete machine must also have an unsolvable halting problem.

Turing complete systems can emulate any other Turing complete system, so if you can build an emulator for some well known Turing complete system in your system, that proves that your system is also Turing complete.

For instance, suppose you want to prove that Snakes & Ladders is Turing complete, given a board with an infinitely repeated grid pattern (with a different version on top and left side). Knowing that the 2-counter Minsky machine is Turing complete (which has 2 unlimited counters and 1 state out of a finite number), you can construct an equivalent board where the X and Y position on the grid is the current value of the 2 counters and the current path is the current state. Bang! You just proved that Snakes & Ladders are Turing complete.

Title: What makes a language Turing-complete?


答:
unit tests tend to be commented out rather than reworked.

At which point the code review process says "go fix the unit tests" and this isn't a problem any more :-) If your code review process isn't catching this kind of major flaw in submitted code, then that's the problem.


问:
Objective-C Lesson in Class Design
I have the following classes:

```<code>   Teacher
   Student
   Class (like a school class)
</code>```

They all extend from KObject that has the following code:

```<code>- initWithKey
- send
- processKey
</code>```

Teacher, Student Class all use the functions processKey and initWithKey from KObject parent class. They implement their own version of send. The problem I have is that KObject should not be instantiated ever. It is more like an abstract class, but there is no abstract class concept in objective-c. It is only useful for allowing subclasses to have access to one property and two functions.

What can I do so that KObject cannot be instantiated but still allow subclasses to have access to the functions and properties of KObject?

答:
KObject could have a single init method init:secret
In this way, only callers with the shared secret would be instantiated.
One downside, however, is that the subclasses would have to know this code to pass.</p>

Title: Objective-C Lesson in Class Design


问:
Declaring multiple licences in a GitHub project
For years, I've been a great fan of putting licences on things shared online to make it easier for others to determine if and how they can reuse said things. Before GitHub began to gently 'push' its users to include LICENSE files with their repos, I didn't really know how to best do this with code – particularly code publicly shared on GitHub! – but I've tried to make good use of LICENSE files ever since.

I'm now in the situation where I've worked on a small project with some other folks, which requires mention of several licences (due to 3rd-party code & libraries as well as non-code files). While my partners go about the issue rather 'sloppily' – it was suggested I 'just put the code online as-is, no-one will care' –, I'd rather do this properly. Problem is: I don't know how one is supposed to make mention of several (different) licences on GitHub.

I've seen several different solutions on GitHub, which is why it's hard for me to judge if this answer to a slightly different question is authoritive. What I'd like to know is which of the following – if any – is the most common, or if there are other, additional ways of doing this.

Create one single LICENSE file and put the descriptions of all the different licences in there. (Questions: Should they be put in a particular order? Would I start off the file with mention of the names of all the licences contained within, for a better overview)?

Create one LICENSE file per licence used and name them LICENSE.md, LICENSE.LibNameA.md, LICENSE.AssetsB.md etc. as suggested in the linked answer. (Question: The naming would be based on project names? Not licence names? If I used more than one licence for self-contributed material, would I mention them all in the 'main' LICENSE.md? If not, what would I do instead?)

Create two LICENSE files: one listing the licence(s) for the 'main' contents, i.e. all code/assets oneself has created; one for all 3rd party materials. (Questions as above: is there a particular naming scheme one would use, and order in which one would list the 3rd party materials?)

Lastly, if I understood the various GitHub explanations and projects regarding their Licenses API correctly, only the 'main' LICENSE file will be taken into consideration when determining a repo's licence (though I haven't been able to figure out which licence would be picked if several were mentioned).

答:
You can use any mechanism to include those licenses that you like, as long as it becomes clear to a visitor of your project which license is applicable to which portion of the project.

My preference would be:

Put each third-party library that you use in a directory of its own. This directory should contain all files that are part of the library's distribution, including the license and readme files.

In your own license file, refer only to the license of your own code

In the readme file of your project, mention which third-party libraries you use and which license each library is distributed under. For full license details, refer to the license file in the library's directory.


答:
I can only think of one argument against unit tests, and it's pretty weak.

Unit tests show the majority of their worth when you refactor or change code at a later stage. You see a huge reduction in the time required to add features and ensure you haven't broken anything.

However: There is a (small) cost in time of writing tests in the first place though.

Therefore: If a project is short enough and not requiring ongoing maintenance/updates it is possible that the cost of writing tests outweighs their benefits.


答:
The abstract concept does not exist in Objective-C, but what may help you are Protocols.

Other workaround is to set the default implementation to raise an exception. But there is a problem with this solution, you can only see if something is wrong during the runtime, but will not get errors during compilation, like you would in Java or C#, for example.

However, before developing any further, I think there is a bigger problem with your application, the design itself. Your inheritance may be broken.

Unless the only methods the Teacher, Student and Class classes use aren't the methods initWithKey, send and processKey, your are inherently breaking the LSP, and should probably go with composition instead.

Title: Objective-C Lesson in Class Design

Body:
I have the following classes:

```<code>   Teacher
   Student
   Class (like a school class)
</code>```

They all extend from KObject that has the following code:

```<code>- initWithKey
- send
- processKey
</code>```

Teacher, Student Class all use the functions processKey and initWithKey from KObject parent class. They implement their own version of send. The problem I have is that KObject should not be instantiated ever. It is more like an abstract class, but there is no abstract class concept in objective-c. It is only useful for allowing subclasses to have access to one property and two functions.

What can I do so that KObject cannot be instantiated but still allow subclasses to have access to the functions and properties of KObject?


问:
Is 4-5 years the “Midlife Crisis” for a programming career?
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

答: Welcome to the real world...unfortunately, what you describe happens in most careers with people which just aren't passionated enough about what they're doing. There's only one option (that is, if you love your work): you must find a better shop to work for, though that is not easy in the current days....</p>

OwnerDisplayName: Luis Abreu


答:
When major code changes occur (new set of POJOs, major application refactoring, etc.), unit tests tend to be commented out rather than reworked.

I always try to keep refactoring and change of functionality separate. When I need to do both, I usually commit the refactoring first.

When refactoring code without changing functionality existing unit tests are supposed to help ensure that refactoring does not accidentally break functionality. So for such a commit I would consider disabling or removing unit tests to be a major warning sign. Any developer doing it should be told not to do so when the code is being reviewed.

It is possible that changes which do not change functionality still cause unit tests to fail due to flawed unit tests. If you understand the code you are changing then the cause of such unit test failures is usually immediately obvious and easy to fix.

For example if a function takes three arguments a unit test covering the interaction between the first two arguments for the function might not have taken care to provide a valid value for the third argument. This flaw in the unit test may be exposed by a refactoring of the tested code, but is easy to fix if you understand what the code is supposed to do and what the unit test is testing.

When changing existing functionality it will usually be necessary to also change some unit tests. In this case unit tests help ensure that your code changes the functionality as intended and doesn't have unintended side effects.

When fixing bugs or adding new functionality, one usually need to add more unit tests. For those it can be helpful to commit unit tests first and commit the bug fix or new functionality later. That makes it easier to verify that the new unit tests did not pass with the older code but do pass with the newer code. This approach is not entirely without drawbacks though, so there also exist arguments in favor of committing both new unit tests and code updates simultaneously.

Time is better spent on integration tests covering use cases, which make the smaller-scoped tests less/not-at-all important.

There is some element of truth to this. If you can get coverage of the lower layers of the software stack with tests targeting the higher layers of the software stack, your tests may be more helpful when refactoring code.

I don't think you'll find an agreement on the exact distinction between a unit test and an integration test though. And I wouldn't worry if you have a test case which one developer call a unit test and another call an integration test, as long as they can agree that it is a useful test case.


问:
Am i looking at HTML / Django the wrong way?
So I'm comfortable programming in Python, I love the minimalist nature of the language. However, I haven't been exposed to any Django yet.

I do know html, css etc for web design but when making websites is it essentially doing either

1) The usual route: HTML, CSS,

or

2) Using Django

My understanding is that both the above can also be integrated with PHP, MySql, Javascript technologies.

Looking at www.reddit.com, I notice when I click view page source it doesn't seem to have the usual html (I know that reddit is made using Django)

Looking at another website eg www.cake.com, it seems to have the usual html.

Looking at both the above made me arrive at the conclusion that a website uses either Django or HTML/CSS only (not both at the same time).

This is my thought process.

答:
Django is a framework for building web applications with Python.

As it sounds like you might not know what these concepts are and are thus confused, I'll try to give a quick overview over what this means:

A framework gives you additional tools (libraries) to work with a programming language. It basically makes working with the language in certain contexts easier from the start as you don't have to build every tool you want to use from scratch. For example, connecting a website with a database might be made easier by using shortcuts (provided by the framework) for interacting with the database.

A web application is a website that reacts to user interaction. It doesn't only serve static content (the HTML and CSS you see in your browser) but dynamically serves content. Based on user input, your web application might e.g. retrieve information from a database and display it, or it might provide a way for the user to authenticate with the website (by checking credentials).

Django is one such web application framework, and Python is the programming language it is built on. There are other frameworks out there that make creating web applications easier, which are based on other languages (e.g. Ruby on Rails, often shortened to just Rails, which is based on the Ruby programming language). There are also other Python-based web application frameworks, which you could use instead of Django, e.g. Flask. As different frameworks provide different functionality and some might be better-suited for some tasks than others, it would make sense to look for online comparisons before picking one.

I have never worked with pure Python combined with HTML + CSS (like you'd combine HTML/CSS and PHP code in one document) and don't know if that is even possible and how one would go about it.

If you want to give Django a try, I'd recommend checking out the Django Girls tutorial, which is a very beginner-friendly tutorial available in several languages.


答:
Integration tests are made to check whether the system behaves as it's supposed to, which always has business value.  Unit tests don't always do that.  Unit tests could be testing dead code, for example.

There's a philosophy of testing that says that any test that doesn't give you information is a waste.  When a piece of code is not being worked on, its unit tests are always (or nearly always) going to be green, giving you little or no information.

Every testing method will be incomplete.  Even if you get 100% coverage by some metric, you still aren't going through nearly every possible set of input data.  So, don't think unit tests are magic.

I've often seen the claim that having unit tests improves your code.  In my opinion, the improvements that unit tests bring to code are in forcing people who aren't used to it to break their code into small, well-factored pieces.  If you get used to designing your code in small, well-factored pieces normally, you may find that you don't need unit tests to force you to do that anymore.

Depending on how heavily you unit test and how big your program is, you may end up with an enormous amount of unit tests.  If so, big changes become harder.  If a big change causes a lot of failed unit tests, you can refuse to make the change, do a lot of work to fix a lot of tests, or throw the tests away.  None of the choices are ideal.

Unit tests are a tool in the toolbox.  They're there to serve you, not the other way around.  Make sure to get out of them at least as much as you put in.


问:
A CLR SQL Server Stored Procedure calling an ASP.NET Web API
We are developing a big system with SQL Server database, ASP.NET Web API 2.2 services and another external services.

We need to load more data on a table while we process the current data on it. To allow load data in background we call our ASP.NET Web API from a CLR SQL Server Stored Procedure.

Then, our ASP.NET Web API retrieve more data and itself insert that data on SQL Server.

Better explained the process is the following:

SQL Server Stored procedure detects that we need more data, then it calls CLR SQL Server Stored Procedure.

CLR SQL Server SP calls ASP.NET Web API.

ASP.NET Web API retrieves more data and insert then into SQL Server.

What do you think about this 'architecture'? Do you know a better approach?

My doubt here is second step: a SQL Server database calling an ASP.NET Web API. But we need to do that work in background.

And also, the new data that we need to insert into SQL Server could be in a WCF SOAP Service.

答:
Based on Ewan's response, I can propose a way to do your work without using CLR:

1) You create a job (windows service, application run by a scheduled task etc.) that checks if extra data is required

2) Fetch the data from the job by calling the Web.API

3) Do your processing in the job. If the logic is convoluted, C# is way better than SQL

4) Persist the data from the job. Persistence can be done using BulkInsert for better performance.

High level languages like C++, C#, Java are almost always more fit to be used for defining business logic. They perform much better in iterative cases, allow OOP, advanced logging, exception management, debugging etc.

If migrating the stored procedure is not an option, you can still do your job:

3) persist fetched data into some buffer tables which have a processing session identifier. If fetched data volume is high, bulk insert is your friend

4) call the procedure using the processing session identifier. The procedure will get data from your buffer tables

5) if data volume is very high, you can empty (truncate) buffer tables during a low usage period, as deletes have great impact upon performance


答:
Using Django does not mean rejecting HTML. You can use Django to create Angular.JS sites, REST API's, SOAP API as well as regular sites with 'normal' HTML.

Most of the time Django is ORM engine and URL routing. Additionally, it may be combined with the template engine and integrated "CMS".

Title: Am i looking at HTML / Django the wrong way?

Body:
So I'm comfortable programming in Python, I love the minimalist nature of the language. However, I haven't been exposed to any Django yet.

I do know html, css etc for web design but when making websites is it essentially doing either

1) The usual route: HTML, CSS,

or

2) Using Django

My understanding is that both the above can also be integrated with PHP, MySql, Javascript technologies.

Looking at www.reddit.com, I notice when I click view page source it doesn't seem to have the usual html (I know that reddit is made using Django)

Looking at another website eg www.cake.com, it seems to have the usual html.

Looking at both the above made me arrive at the conclusion that a website uses either Django or HTML/CSS only (not both at the same time).

This is my thought process.


答:
Separating getOutput($input) from generateOutline($input) and testing whether getOutput($input) returns the correct results is an important step.

If the generated pdf requires testing you can test:

Is the generated PDF a valid PDF: via tools such as Apache PDFBox (this one is in Java but PHP equivalents do probabably exist) or an online validation tool.

Does the generated PDF contain the expected data: using tools such as pdf_search, see also https://stackoverflow.com/q/1882318/814206.

Automatically testing the UX part of testing the generated PDF is more difficult (I don't know whether tools for these tests exist).:

Is the PDF readable?

Is the layout correct?

Does is follow typesetting best practices?

Title: What technique can I use to test my code when code renders out an untestable(?) PDF document?

Body:
I have a need to test output of my code before I send the output for PDF rendering.

Currently I have decided on a switch statement that does two different things depending on whether I am in production or in testing mode.

Render PDF with data that goes on PDF in a web browser.  Nothing is returned to caller

Do not render the PDF but just return the data for test/other purposes

Just to show some code to clarify ...  Here is what I have now:

```<code>$output = $this->prepOutputData();
switch ($this->strategy)
{
    //outputs binary PDF, no return statement
    case OutlineStrategy::PDF_STRATEGY:
        $pdfEngine = new PdfEngine();

        $em = DoctrineConnector::getEntityManager();
        $metaData = $em->getRepository(PdfMetadata::class)->findAll();

        $pdfEngine->arrangeDataOnPdf($metaData, $output);
        $pdfEngine->printPdfToBrowser();
        break;

    //returns data that goes onto PDF
    //for testing or for consumption by non-PDF entity
    case OutlineStrategy::TEST_STRATEGY:
        return $output;
        break;
}
</code>```

Goal

My goal is to be able to show PDF in production but NOT show PDF for testing and yet to be able to run test checks on the $output data.  How can I do that?


答:
I tend to side with your friend because all too often, unit tests are testing the wrong things.

Unit tests are not inherently bad. But they often test the implementation details rather than the input/output flow. You end up with completely pointless tests when this happens. My own rule is that a good unit test tells you that you just broke something; a bad unit test merely tells you that you just changed something.

An example off the top of my head is one test that got tucked into WordPress a few years back. The functionality being tested revolved around filters that called one another, and the tests were verifying that callbacks would then get called in the correct order. But instead of (a) running the chain to verify that callbacks get called in the expected order, the tests focused on (b) reading some internal state that arguably shouldn't have been exposed to begin with. Change the internals and (b) turns red; whereas (a) only turns red if changes to the internals break the expected result while doing so. (b) was clearly a pointless test in my view.

If you have a class that exposes a few methods to the outside world, the correct thing to test in my view are the latter methods only. If you test the internal logic as well, you may end up exposing the internal logic to the outside world, using convoluted testing methods, or with a litany of unit tests that invariably break whenever you want to change anything.

With all that said, I'd be surprised if your friend is as critical about unit tests per se as you seem to suggest. Rather I'd gather he's pragmatic. That is, he observed that the unit tests that get written are mostly pointless in practice. Quoting: "unit tests tend to be commented out rather than reworked". To me there's an implicit message in there - if they tend to need reworking it is because they tend to suck. Assuming so, the second proposition follows: developers would waste less time writing code that is harder to get wrong - i.e. integration tests.

As such it's not about one being better or worse. It's just that one is a lot easier to get wrong, and indeed very often wrong in practice.


答:
One necessary condition is a loop with a maximum iteration count that is not determined ahead of the iteration, or recursion where the maximum recursion depth is not determined ahead. As an example, for ... in ... loops as you find them in many newer languages are not enough to make the language turing complete (but they will have other means). Note that this doesn't mean limited number of iterations or limited recursion depth, but that the maximum iterations and recursion depth must be calculated ahead.

For example, the Ackermann function cannot be a computed in a language without these features. On the other hand, a lot of highly complex and highly useful software can be written without requiring these features.

On the other hand, with every iteration count and every recursion depth calculated ahead, not only can it be decided whether a program will halt or not, but it will halt.

Title: What makes a language Turing-complete?

Body: What is the minimal set of language features/structures that make it Turing-complete?</p>


答:
When major code changes occur (new set of POJOs, major application
  refactoring, etc.), unit tests tend to be commented out rather than
  reworked.

Don't do that. If you find someone who does that, murder them and make sure they do not reproduce, as their children might inherit that defective gene. The key as I see it from watching CSI television shows is to scatter a lot of misleading DNA samples everywhere. This way you pollute the crime scene with so much noise that, given the costly and time-consuming nature of DNA testing, the probability that they'll pin it down to you is astronomically low.


答:
A few ramblings from someone who is wondering if after 40+ years of hacking, maybe a new career might be in order ... :-)

Nah.  I love this stuff.  From punch cards and paper tape, through the CDC mainframes, PDP-*, 4004, Alpha, Nova, Eclipse, Eagle (the hardware which came long before the software), Mac Minis and all the stuff in between.  And there are a few of us who still are curious about new technologies after many, many have come and gone.  My first confession is how, as a child of the Mini-computer industry I looked at the old fogies of the Cobol/Mainframe era and thought them dated and basked in the knowledge that us young whipper snappers were here to save the technological day and get stuff done, not to mention make millions.

In all that time I never seriously thought of actually leaving programming because there was just too much left undone.  Much of it work created by clueless management in a rush to deliver a 5 month baby, time after time after time.  And it is that work that is the bulk of the uninteresting work done by 9-5ers or by off-shoring.

The interesting stuff is being done by startups, small companies, and companies like Apple and Google who for different reasons have created work environments that foster creative programming.  And in big companies with dysfunctional work environments by mavericks who are willing to be stick their necks out and have their heads lopped off from time to time.  Been there, done that and will do it yet again, if only because at the end of the day, there is just nothing like seeing that application, system or library actually working and being used, and most important of all, knowing that but for your efforts, the end product would be worse off still.

Not to worry.  If you love this stuff you will be doing it 30 years from now.  If not you will, with any luck, find what you do love and it will lead to internal satisfaction and hopefully lots more.  In any case, excellent question if only for the opportunity to express some deeply felt passion.


答:
First of all: this has nothing to do with interfaces which are defined by the keyword of the same name.

The advice means nothing else than not to rely on a concrete implementation, rather on a well defined abstract behaviour.

My knowlede of PHP is near 0 - so I apologize answering in a more general way.

Say you have an e-commerce application and domain-objects like order. Every order was created on some point in time. Oftentimes there are filteringoperations to get a subset of orders within a given timeframe. You could write conditions like order.getCreated() > concreteDate. Besides other code smells, this is bad for another reason:
You tie your code to the implementation fact, that the > operation works with your code. If the implementation of the date is ever changed - say you use another Date object with other operators (e.g. .after()), your code is broken.

If you designed the order in a proper way, you would define the operation as order.createdAfter(date), you define an interface aka. a well defined way to get information you need from an order, which is itself independed from the concrete implementation. The input is a Date and the result is a boolean.

It is allways good practice to choose the most abstract datatype for returnvalues to prevent assumptions (= dependencies) on concrete implementations. For example, it would be good practice in Java to return Iterable<T> instead of concrete List to prevent assuptions about the behaviour of the resulting collection.

tl;dr

Read interface as well defined behaviour independent from concrete implementations.

Title: How to "program to an interface"


答:
Unit test are definitely not the silver bullet some proponents claim them to be. But in general they have a very positive cost/benefit ratio. They will not make your code "better", maybe more modular. "better" has so many more factors than what "testability" implies. But they will assure it works in all the cases and usages you thought about, and will eliminate most of your bugs (probably the more trivial ones).

The greatest benefit of unit tests though is they make your code more flexible, and resilient to change. You can refactor or add features, and be pretty confident you didn't break anything. This alone makes them worthwhile for most projects.

Referring to the points made by your friend:

If adding POJOs breaks your unit tests then they are probably very badly written. POJOs are usually the language you are using to talk about you domain, and the problems you are solving, changing them obviously means your entire business logic, and probably presentation code must change. You can't expect what's assuring those parts of your program works not to change...

Complaining that Unit tests are bad, because people comment them out, is like complaining seat belts are bad because people don't wear them. If one comments out testing code and breaks something, he should end up in a very serious and unpleasant conversation with his boss...

Integration tests are far superior to unit tests. no question. especially if you are testing a product. But writing good, comprehensive integration tests, that will give you the same value, coverage and assurance of correctness that unit test give you, is incredibly hard.