问:
Likes / Stars / Following - same or separate data structures?
I am building a social network, which will have standard features of 'likes' (upvotes) for posts, 'following' between users and 'stars' for favorite posts. These might reasonably expand in the future for similar functionality.

I am mostly using NoSQL (namely, MongoDB docs) but would appreciate an SQL perspective as well.

I am planning on persisting these in collections which might hold documents as following:

Followers Collection, example doc: {follower_id: 123, followee_id: 456}

Likes Collection, example doc: {liker_id: 123, post_id: 789}

Stars Collection, example doc: {user_id: 123, starred_item_id: 555}

The emerging structure seems very similar. Some additional data may be identical (creation date?), and while other might be different (type of item liked/starred/followed, and/or additional, type-specific fields [say a numerical value for a 'rating' class]), there appears to be so much in common that it might be prudent to consolidate all of these into a similar 'model', both in terms of a single DB collection (or SQL table) as well as shared/single code model.

I am mostly concerned about:

Collection growing too large - this is already a concern just for 'likes', it might be exacerbated (although only by ~*3) by throwing in 'stars' and 'followers' too.

Logic between these data objects growing apart over time, making using a shared data model wrong.

So, would this be a good idea? Likes/Stars/Following - are they more similar or more separate?

Most specifically, assuming 3 collections which are similar but not identical, would it make more sense to consolidate them into one or keep them separate? Both considering code complexity (and DRYness) and DB constraints (e.g. index size).

答:
Since Likes and Stars(favorite) pertain to the same object, a "post". A unifying domain could be used to store Likes and Stars such as postIcons: {userId: '123', postId:'789', like: true, star: true}. You would have an entry for every post your user liked or favorited but would only have one record for a post your user liked and favorited.

'Followee' pertains to another user. So your user can follow many other users.  Sounds like Follows could be a List of ids on a user object such that your user has many 'followeeIds'.

In your comment where you have an 'action_type' you would have a record for the same user and the same item for each 'action_type'.


问:
Having one server for the whole team
I'm currently in a team where it lacks of its resources. The dev't team had only one websphere server for testing and we could not deploy our project in our local desktop because the websphere is only installed in one unit. Hence, every one is waiting after another in testing their fixes and feature. I tried to ask the manager if we could have our own copy of websphere installed in our local desktop but the manager is questioning us why we need it. I said some of the reason, but I guess the manager is still in doubt.

The question now is, in a development team, is having your own local application server installed in your desktop part of a best practices? how and why? what are the benefits? or what are the cons and pros?

答:
I don't know if it's a best practice but I like to have a development environment as complete as possible. Including application server, database and external applications that are invoked during execution if possible.

This allows me to develop independent from others. I can redeploy and restart servers when I need. I can fill my database with my test data, and restore it when I need. I can install different versions of components. And when I need to debug, I can start a server in debug mode or change the logging configuration.

It also makes it more easy to try new things, like change server configuration settings, or develop automation scripts.

By using virtualization software like Virtualbox, together with tools like Vagrant or Docker, maintaining and sharing preconfigured server instances gets quite easy.

As a start you could try and run a Websphere instance on your development machine. I have worked that way, connecting to a shared database. Perhaps the server is not really fast, but it may be good enough.

ContentLicense: CC BY-SA 3.0

Title: Having one server for the whole team


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
More dereferencing:

```<code>echo something_that_returns_array()[4];
</code>```

Others have mentioned named parameters, and shorter array syntax. I wouldn't mind shorter object syntax, as well.

```<code>$a1 = array(1, 2, 3, 4);
$a2 = [1, 2, 3, 4];

$b1 = (object)array('name' => 'foo');
$b2 = {'name' => 'foo'}; // or something?
</code>```

ContentLicense: CC BY-SA 2.5

Body:
More dereferencing:

echo something_that_returns_array()[4];

Others have mentioned named parameters, and shorter array syntax. I wouldn't mind shorter object syntax, as well.

$a1 = array(1, 2, 3, 4);
$a2 = [1, 2, 3, 4];

$b1 = (object)array('name' => 'foo');
$b2 = {'name' => 'foo'}; // or something?


问:
Can multiple CPU's / cores access the same RAM simultaneously?
This is what I guess would happen:

If two cores tried to access the same address in RAM, one would have to wait for the other to access the RAM.  The second time that each core would try to access the same address, they may still have that RAM cached, so they could access their respective caches simultaneously.

If two cores tried to access different addresses in the same RAM, one would have to wait for the other to access the RAM.

In other words, I would imagine that for RAM intensive programming tasks, multiprocessing won't help much unless it involved reading from the same address in RAM multiple times per core.

So, can multiple CPU's / cores access the same RAM simutaneously, or is what I'm saying correct?

答:
Although most answers approach from the side of software and/or hardware model, the cleanest way is to consider how the physical RAM chips work. (The cache is located between the processor and the memory, and simply uses the same address bus, and its operation is completely transparent for the processor.)
RAM chips have one single address decoder, which receives the address of the memory cell, arriving on the address bus (and similarly a data bus, either in or out). The present memories are built in the "single processor approach", i.e. one processor is connected through one bus to one memory chip. In other words, this is the "von Neumann bottleneck", since every single instruction must reference the memory at least once.
Because of this, on one wire (or wires, aka bus) only one signal may exist at a time, so the RAM chip may receive one cell address at a time. Until you can assure the two cores put the same address to the address bus, the simultaneous bus access by two different bus drivers (like cores) is physically not possible. (And, if it is the same, it is redundant).

The rest is the so called hardware acceleration. The coherence bus, the cache, SIMD access, etc. are just some nice facades in front of the physical RAM, your question was about. The mentioned accelerators may cover the fight for using the address bus exclusively, and the programming models have not much to do with your question. Also note that simultaneous access would also be against the abstraction "private address space".

So, to your questions: the simultaneous direct RAM access not possible, neither with the same nor with different addresses. Using cache might cover this fact and might allow apparently simultaneous  access in some cases. It depends on cache level and construction, as well as the spatial and temporal locality of your data.
And yes, you are right: multi(core) processing without enhanced RAM access, will not help much for RAM-intensive applications.

For better understanding: just recall how Direct Memory Access works. Both the CPU and the DMA device can put address to the bus, so the have to exclude each other from the simultaneous using of the bus.

ContentLicense: CC BY-SA 4.0


问:
Software piracy and GPL
Consider the case below:

A Wordpress plugin must be GPL since Wordpress itself is GPL

There are some plugin authors selling premium WordPress plugins, and assume the authors are okay with the GPL license, and so they make money by providing support in their forum (1yr only after purchase, e.g. $100 for 1st year, you enjoy plugin download and ask question in the forum)

Now, a theft purchase the plugin for $100 and want to re-sell the GPL-ed plugin in another website for just $10.

Can the original authors do something to the theft?

答:
What you describe appears to be perfectly legal.

The GPL allows any licensee (anyone who bought it) to sub-license it to others for any price they want or even for free when they feel generous. Those other people are now also licensees who can also sell or gift the software to others. So when someone offers a GPL software for $100, and you want to pay less, you can seek out any of the people who already bought it and ask them if you can buy it from them for less. This is perfectly legal and intended. The only downside is that you won't get the support service offered by the original creator, because that's a completely independent contract not covered by the GPL. But when you need help with the software, you can make a support contract with anyone else you consider qualified.

However, that only applies to people who actually did receive the program under the conditions of the GPL, either directly or through any number of sub-sub-sub-licensees. Should one steal a copy of a GPL program illegally (through hacking, for example), they are not licensees, which means they do not have the right to sub-license it, and are violating the copyright of the original author when they do.

<advertising>When you have more questions about how one can monetize GPL software, you might want to commit to the new proposal Open Source Stackexchange. It still needs people to commit to it so it can go into beta phase.</advertising>

Title: Software piracy and GPL


问:
How to make variables inherent to an object or system
How can one make variables inherent to an object or system?

For example, when creating a web browser, each option that is created for the user to have control over (i.e. how a window opens, if downloads start immediately, if a download window opens or not, etc.) must be checked on every single event that involves this object or system using disgusting if-blocks.

Is it possible to make these features inherent to the system, such that they need not be checked again once the configuration has been modified?

(*I may be trying to make a non-constant variable be a constant after it is set, but I'm not sure, because I am still grasping at this concept that popped into my mind and may not make sense due to the nature of computers and how they must check every single thing every single time, which we don't mind so much since they do it all so darn fast.)

ADDENDUM:

This question came to me when I was thinking about ASIC design versus universal computing. Analog systems are naturally faster because they just "are", but at the cost of non-adaptability. We created more univeral models (desktop computers) and higher level languages to allow for this adaptability, but at the cost of speed. The speed reduction is a result of the additional overhead and many other things, one of these many things being constant state checking which is realized in the form of 'disgusting if-blocks'. So I suppose that I am looking for a way to simulate the static analog property in a dynamic system.

I thought of this problem further when I used my arm earlier today: my arm 'just was', and I didn't need to check if it was still attached and functional, or explain to it how to brush my teeth... it just knew! When did I lose you?

答: "disgusting if-blocks" can be avoided by using polymorphism to replace conditionals, or more specifically, by  applying the strategy pattern. In your example, one could have objects representing a "window open" strategy, a "download strategy", a "download window opening strategy", and so on.


问:
Securing a Web Api for individual Users
We currently have a web app (.net MVC 5), user's login using their username and password and then we store an encrypted value in a cookie to authenticate them on future requests.

We are now in the process of designing an API for that will be mainly used by our mobile app (will be built once the API is ready).

What I/we are trying to understand is the best way to secure requests made to the API. Our current plan is to have a simple API method that accepts a username and password, which will then validate these details and on success return a token that is unique to that user. This token will then be used on each subsequent request to authenticate.

The issue here is that if that token is stolen then someone could impersonate that user quite easily. So should we be sending back some kind of token secret that we can use to sign each request (using something like HMAC) then this can be checked on the server before allowing the request to continue?

答:
Token over https is a time-tested and proven approach for securing a web api. If the token is stolen somehow, via an attack on ssl, it will only be valid for a short time. Consider using Thinktecture's identity server, which has a token server built in.

https://github.com/IdentityServer/IdentityServer2

Whatever you do, resist the urge to re-imagine this problem and construct a custom solution. You are likely to introduce security holes that you won't have community support to detect and fix.

Title: Securing a Web Api for individual Users


问:
as a team: multiple projects vs single project?
I've been wondering for a while. I guess I have been adapting to the circumstances but I am in desperate need of some clearly defined workflows.

Ok, so say I am working with one other person and I have 2 projects come up both of equally large size with LOOSE deadlines. What should I do:

a) turn down one, work on other
  exclusively

b) take both on and develop both
  simultaneously

c) assign one person to each project

I have done c in the past which works fine. As a manager also, I've simply had to manage that project while I work on another. No big deal. But what is the ideal option above?

I'd hate to do a because I am turning down work either though deadline would permit working on both projects.

Any input?

Following things should be taken into account:

-) all members have same expertise in design & development and can
  effectively function as freelancers

-) timezones may not be the same so they would not be working at the same
  time

答:
At my job I work in a small team and everyone is assigned to all projects for a couple of reasons:

If someone gets hit by a bus, there is someone else to step in

Even if all team members are equally experienced, people will still have preferences or experience for certain tasks

It keeps the team more involved

Context switches can improve productivity (when applied carefully)

I have to say though that sometimes I wished I had just one thing going on to focus on, and nothing else, while other times I welcome the relief of being able to have something else to do.


问:
Is directly using Make considered obsolete?
So I have been coming across many comments/posts/etc regarding creating makefiles directly, and how it is a silly thing to do in 2015. I am aware of tools such as CMake, and I actually use CMake quite often. The thing is, CMake is just creating the Makefile for you and helping to remove the tedium of doing it yourself. Of course it adds a lot of other great features... but its still a Makefile in the end.

So my question is, is the 'obsolete' talk regarding make referring to the entire Make utility, or just the idea of manually writing your own Makefiles? I do not use an IDE for C/C++ development at all (just emacs), so I have always written Makefiles.

If Make is considered outdated, what should a C/C++ dev be using to build small, personal projects?

答:
The big difference is that CMake is a cross-platform meta-build system. A single CMake project can produce the usual Unix/Linux makefile, a Visual Studio project for Windows, an XCode project for Mac, and almost any other non-meta build system you might want to use or support.

I wouldn't say using make directly or even manually editing makefiles is "obsolete", but those are things you probably shouldn't do unless you are working on Unix/Linux stuff that won't need porting to Windows, much like how you should not be editing Visual Studio project files directly if you ever want to port them to not-Windows. If you have any interest in portability, it's worth learning a meta-build system like Scons or CMake.


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答:
Null is evil.  However, the lack of a null can be a greater evil.

The problem is that in the real world you often have a situation where you do not have data.  Your example of the version without nulls can still blow up--either you made a logic mistake and forgot to check for Goodman or perhaps Goodman got married between when you checked and when you looked her up.  (It helps in evaluating the logic if you figure Moriarty is watching every bit of your code and trying to trip you up.)

What does the lookup of Goodman do when she's not there?  Without a null you have to return some sort of default customer--and now you're selling stuff to that default.

Fundamentally, it comes down to whether it's more important that the code work no matter what or that it work correctly.  If improper behavior is preferable to no behavior then you don't want nulls.  (For an example of how this might be the right choice consider the first launch of the Ariane V.  An uncaught /0 error caused the rocket to make a hard turn and the self-destruct fired when it came apart due to this.  The value it was trying to calculate actually no longer served any purpose the instant the booster was lit--it would have made orbit despite the routine returning garbage.)

At least 99 times out of 100 I would choose to use nulls.  I would jump for joy at note to self's version of them, though.

Title: Are null references really a bad thing?


问:
Agile: How to deal with bottle neck approvals outside of SCRUM?
Is there an Agile term for when there is a stakeholder that acts as a bottleneck by jumping in only occasionally to trump decisions made collectively by the team? (ie, upper management who never partake in the process, but will occasionally review work and decide they don't like it)? I'm familiar with Pig and Chickens. Would this simply be a 'type of chicken'?

Is there any Agile technique to deal with said type of person? Is there a particular role on the Agile team that should be in charge of managing this type of issue?

An example might be that the product owner is happy, IT is happy, UX is happy, various business roles are happy, and sprints are underway, but suddenly someone's boss's boss has decided they want everything put into a PPT deck for them to 'approve' where we're at.

答:
This is the Product Owner's job.

The whole point of  the product owner is to act as the point of contact between all the stakeholders (including people like someone's boss's boss) and the team itself.  In theory, the rest of the team should only ever have to deal with the Product Owner.  The Product Owner goes and does all the work of talking to various stakeholders, puts together the stories, and then the team just works on them in order of the set priority, and ignores who requested what.  (In practice, it never quite works this way, but close enough.)

However, it is also important to remember what a stakeholder is.  A stakeholder is the person who writes the checks.  The team gets a list of business requirements, and then fulfills them.  Sometimes you get stakeholders who either want something stupid, or who change their mind over and over.  That is, unfortunately, their prerogative, after all, the whole point of agile is to let stakeholders change their minds often and to catch stupid decisions faster.  Ideally, it is mostly the Product Owner that deals with the stress of all that while the team just takes the stories as they come.  Really, the whole point of agile is for stakeholders to determine they don't like something and actually want something different.

Now this is all business requirements.  If this boss's boss is mucking about with technical decisions, then, well, you have my sympathy.  There is no real Agile term for this other than "not agile".  In Agile, the team makes technical decisions, not the stakeholders.

TL;DR - If a stakeholder is overturning business decisions, then this is their prerogative, and it is the Product Owner job to deal with that.  If the stakeholder is overturning technical decisions, or overturning any decision mid-sprint, then this is something the Product Owner and Scrum Master should be demanding stop.


问:
Are first-class continuations useful in modern object-oriented programming languages?
Continuations are extremely useful in functional programming languages (e.g. the Cont monad in Haskell) because they allow a simple and regular notation for imperative-style code.  They're also useful in some older imperative languages because they can be used to implement missing language features (e.g. exceptions, coroutines, green threads).  But for a modern object-oriented language with support built in for these features, what arguments would there be for also adding support for first-class continuations (whether the more modern delimited style reset and shift or scheme-like call-with-current-continuation)?

Are there arguments against adding support other than performance and complexity of implementation?

答:
Let's let Eric Lippert answer this one:

The obvious question at this point is: if CPS is so awesome then why
don’t we use it all the time? Why have most professional developers
never heard of it, or, those who have, think of it as something only
those crazy Scheme programmers do?

First of all, it is simply hard for most people who are used to
thinking about subroutines, loops, try-catch-finally and so on to
reason about delegates being used for control flow in this way. I am
reviewing my notes on CPS from CS442 right now and I see that in 1995
I wrote down a profQUOTE: “With continuations you have to sort of
stand on your head and pull yourself inside out”. Professor Duggan (*)
was absolutely correct in saying that. Recall from a couple days ago
that our tiny little example of CPS transformation of the C#
expression M(B()?C():D()) involved four lambdas. Not everyone is good
at reading code that uses higher-order functions. It imposes a large
cognitive burden.

Moreover: one of the nice things about having specific control flow
statements baked in to a language is that they let your code clearly
express the meaning of the control flow while hiding the mechanisms –
the call stacks and return addresses and exception handler lists and
protected regions and so on. Continuations make the mechanisms of
control flow explicit in the structure of the code. All that emphasis
on mechanism can overwhelm the meaning of the code.

In the next article, he explains how asynchrony and continuations are exactly equivalent to one another, and goes over a demonstration of taking a simple, (but blocking,) synchronous network operation and rewriting it in asyncronous style, making sure to cover all the hidden gotchas that have to be covered in order to get it right.  It turns into a massive mess of code.  His summary at the end:

Holy goodness, what a godawful mess we’ve made. We've expanded two
lines of perfectly clear code into two dozen lines of the most
godawful spaghetti you've ever seen. And of course it still doesn’t
even compile because the labels aren’t in scope and we have a definite
assignment error. We;d still need to further rewrite the code to fix
those problems.

Remember what I was saying about the pros and cons of CPS?

PRO: Arbitrarily complex and interesting control flows can be built out of simple parts – check.

CON: The reification of control flow via continuations is hard to read and hard to reason about – check.

CON: The code that represents the mechanisms of control flow completely overwhelms the meaning of the code – check.

CON: The transformation of ordinary code control flow into CPS is the kind of thing that compilers are good at, and almost no one else
is – check.

This is not some intellectual exercise. Real people end up writing
code morally equivalent to the above all the time when they deal with
asynchrony. And, ironically, even as processors have gotten faster and
cheaper, we spend more and more of our time waiting for stuff that
isn’t processor-bound. In many programs, much of the time spent is
with the processor pegged to zero waiting for network packets to make
the trip from England to Japan and back again, or for disks to spin,
or whatever.

And I haven't even talked about what happens if you want to compose
asynchronous operations further. Suppose you want to make
ArchiveDocuments an asynchronous operation that takes a delegate. Now
all the code that calls it has to be written in CPS as well. The taint
just spreads.

Getting asynchronous logic right is important, it’s only going to be
more important in the future, and the tools we have given you make you
“stand on your head and turn yourself inside out” as Professor Duggan
wisely said.

Continuation passing style is powerful, yes, but there's got to be a
better way of making good use of that power than the code above.

Both articles, and the following series on a new C# language feature that moves all this mess into the compiler and lets you write your code as normal control flow with a special keyword to mark certain parts as asynchronous, are well worth reading even if you're not a C# developer.  I'm not, but it was still quite the enlightening experience when I ran across it for the first time.


问:
How much Code Coverage is "enough"?
We are starting a push for code coverage here at my work, and it has got me to thinking.... How much code coverage is enough?

When do you get to the point of diminishing returns on code coverage?  What is the sweet spot between good coverage and not enough?  Does it vary by the type of project your are making (ie WPF, WCF, Mobile, ASP.NET)  (These are C# classes we are writing.)

答:
When you start considering changes that would affect run time performance, security, flexibility or maintainability to allow more code coverage it is time to end the quest for more code coverage.

I have projects where that point is 0% because coverage is impossible to calculate without harming the design and other projects where that is as high as 92%.

Code coverage metrics are only useful in pointing out were you might have missed some tests.  They tell you nothing about the quality of your tests.

Title: How much Code Coverage is "enough"?


问:
Repository matrix pattern?
I'm trying really hard to refactor some of my legacy code in the project using best practices and design patterns + DDD so I'd love some feedback on an issue I'm currently having.

Let's assume that I have two entity classes:

class Dog
{
    protected $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    function bark()
    {
        echo 'Rawr';
    }
}

class Husky extends Dog
{
    /**
     * @var Sledge
     */
    protected $sledge;

    function __construct($name, Sledge $slegde)
    {
        parent::__construct($name);
        $this->sledge = $slegde;
    }

    function pull()
    {
        echo $this->sledge->pull();
    }
}
```

Dog is my regular entity and his only responsibility is to map database fields.
Husky on the other hand has same responsibilities as dog but also delegates Sledge pulling.

Normally, both entities would have different repositories (should they? Since one inherits from one another) to call for, however business requirement implies that client does not have to specify dog's type (so it can either be a "basic" Dog or special Husky), just its name http://localhost/animal/fluffy.

What is more, currently they both reside in the same database table (recognized by type field) and right now there are no technical plans to change that (performance and time reasons).

What is the best way to do it?

Should I create some AnimalRepository, pull the data and treat it as DTO, detect it's type and then create appropriate class?

Should I create some kind of higher abstraction level mapper? How should it look like?

答:
I think that answer to behavior extension cannot be abstracted itself - it depends on concrete problem. If we assume that pulling sledge is unusual dog behaviour* (encapsulate what varies) another level of abstraction would be the answer, but it would be different in case of pulling-sledge-contest-app where a dog can pull sledge in generall, but some are to weak to pull at all or don't have sledge equipped. You may also have some general dog contest where strategy pattern applies with some startCompetition() method.

*) In this context Husky class is not only a Dog, but a composition of a Dog and Sledge. I would start with Husky class signature that would look something like

```<code>class Husky extends Dog implements SledgePullingInterface {}
//or with another level of inheritance
class Husky extends SledgeDog {}
</code>```

Now it's easier to "sniff the code". It looks strange when Husky is not a direct subtype of a Dog - maybe the name should be different? Maybe SledgeDog class is sufficient or race specific classes are separated for another reason? - can't tell.

If you map husky as a dog only (using DogMapper) it cannot be used in Husky class context. Just a dog that happens to be husky which you can tell by getting some 'race' field only - square is a rectangle, but not an abstract one. For a complete Husky class object you need

```<code>new PullingSledgeDogMapper(DogMapper $dog, SledgeMapper $sledge);
</code>```

Title: Repository matrix pattern?

Body:
I think that answer to behavior extension cannot be abstracted itself - it depends on concrete problem. If we assume that pulling sledge is unusual dog behaviour* (encapsulate what varies) another level of abstraction would be the answer, but it would be different in case of pulling-sledge-contest-app where a dog can pull sledge in generall, but some are to weak to pull at all or don't have sledge equipped. You may also have some general dog contest where strategy pattern applies with some startCompetition() method.

*) In this context Husky class is not only a Dog, but a composition of a Dog and Sledge. I would start with Husky class signature that would look something like

class Husky extends Dog implements SledgePullingInterface {}
//or with another level of inheritance
class Husky extends SledgeDog {}

Now it's easier to "sniff the code". It looks strange when Husky is not a direct subtype of a Dog - maybe the name should be different? Maybe SledgeDog class is sufficient or race specific classes are separated for another reason? - can't tell.

If you map husky as a dog only (using DogMapper) it cannot be used in Husky class context. Just a dog that happens to be husky which you can tell by getting some 'race' field only - square is a rectangle, but not an abstract one. For a complete Husky class object you need

new PullingSledgeDogMapper(DogMapper $dog, SledgeMapper $sledge);


答:
if your project is simple and contains very few files, then no make file is needed.

However, when the project is complex, uses numerous memory areas, has many files, then it is necessary to place each memory area in the right spot in the addressable memory, it is highly desirable to not recompile every file every time a trivial change is made to one file,

If you want to erase old files/compile/link/install with the minimum amount of hassle and chance of keypress mistakes, the makefile is a real boon.

When you get into the 'real world' projects rarely ever are just 1 or 2 files, but rather hundreds of files.  a makefile will always perform the right actions and no unnecessary actions (after it is debugged) so you only type one simple command and the makefile does all the work

cmake tries to do the whole build process, while making it as simple as possible for the novice user.

Make enables the user to retain control over the build process

Title: Is directly using Make considered obsolete?

Body:
So I have been coming across many comments/posts/etc regarding creating makefiles directly, and how it is a silly thing to do in 2015. I am aware of tools such as CMake, and I actually use CMake quite often. The thing is, CMake is just creating the Makefile for you and helping to remove the tedium of doing it yourself. Of course it adds a lot of other great features... but its still a Makefile in the end.

So my question is, is the 'obsolete' talk regarding make referring to the entire Make utility, or just the idea of manually writing your own Makefiles? I do not use an IDE for C/C++ development at all (just emacs), so I have always written Makefiles.

If Make is considered outdated, what should a C/C++ dev be using to build small, personal projects?


问:
Why does Java (and other langs too) have seemingly redundant functions like "str.startsWith(String str, int fromOffset)"?
I was wondering why Java and other programming languages implement (seemingly) redundant functions such as:

```<code>"foobar".startsWith("bar", 3);
// same as
"foobar".substring(3).startsWith("bar");

// or even indexOf(str, offset), regionMatches(...)
</code>```

Is there a reason behind this?

答:
These are called convenience functions. They are included so users can write shorter and simpler code.

Note that almost every library is "redundant" in the sense that users could write the same code themselves outside of the library. However the point of using libraries is that you save time and code, and you can reuses the knowledge of the library in different projects.


答:
There are few possible reasons for this sort of thing:

As in JacquesB's answer it may simply be convenience for the library user to call a single method rather than two methods and keep their code more succinct.

Performance may be a consideration. Calling .substring(3) will result in a new string being created, and therefore you are looping over the string twice, it is possible 1 for .startsWith("bar", 3) to be implemented without creating a temporary substring and to just loop through the string once. .startsWith has another tiny optimization point: it can bail out early if the first character does not match, .indexOf will need to keep checking the rest of the string.

Expressing intent: while its fairly obvious what you are doing with either of your two variants it does take the reader a little while to consider the purpose compared to a single method call that will tell you exactly what you are doing.

As Phillipp points out, history can be a factor, adding new methods to an API is fairly easy, changing or removing existing methods is much harder as it will break existing code, so sometimes you may just be seing an artefact of the history of the development of the API 2.

1 I have no idea if this is actually the case here but I'd be surprised if it does.

2 Probably not in this case though.

Title: Why does Java (and other langs too) have seemingly redundant functions like "str.startsWith(String str, int fromOffset)"?

Body:
I was wondering why Java and other programming languages implement (seemingly) redundant functions such as:

```<code>"foobar".startsWith("bar", 3);
// same as
"foobar".substring(3).startsWith("bar");

// or even indexOf(str, offset), regionMatches(...)
</code>```

Is there a reason behind this?


答:
Bring taint support up to latest version and include it in standard builds, preferably turned on in the default config http://wiki.php.net/rfc/taint

This would prevent XSS and SQL injection attacks by making people code properly.

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Databinding When View Differs From Model
I have an entity Customer. Customer has a collection of Accounts. I have corresponding classes. The Customer class has-a List<Accounts>.

I have two views. First page shows the Customer's name, address etc. Each field is data-bound to corresponding property on the Customer object. There is a link show-accounts. On clicking that link, you get a second view. There is a grid which is data-bound to the Accounts property on the customer object.

Now I need to provide a No-of-accounts label on the first view. Problem is there is no such property on the Customer business object. I have a few approaches to do so, but I do not like either of them.

Add a property AccountCount on Customer object. But it is artificial. What if tomorrow I need to show the Balance in the highest account?

Use the Count property on the Accounts list. But this needs the list to be populated. My users rarely view the whole list of accounts. I do not see the point of loading the entire accounts table just to show the count.

Once databinding is complete, make a seperate call from UI directly to Data-Layer. Let a query fetch just the details. This defeats the whole layered/tired architecture. Soon everything falls into chaos, with everyone maintaining this code firing their own queries.

Rather that Data Binding to the business model Customer, I can Data bind to a CustomerViewModel class. This class can have the artificial CountOfAccounts property. This keeps UI specific code separate from BL. Problem is ViewModel class depends on the BO layer, but the BO does not have that property. We can populate the Accounts list and fetch the count from there, but fetching a table for just getting the Count seems overkill.

Question

What can I do when my UI wants things different from the Business Model?

答:
What you are looking for is the concept of a ViewModel.

This is an object that contains only data that the view is interested in, and is very often not a 1 to 1 mapping with a business or domain model. It may be a cut down version of a business model, it may be an amalgamation of multiple different business models.

If your view needs a count, this can represented in the ViewModel. If the view also needs to display all the accounts, then the count can just be pulled from ViewModel.Accounts.Count() (or whatever syntax for your language).

If the view does not need the account list, then it would make sense to then have the account represented by a "NumberofAccounts" (or whatever name you like) property.


问:
pass a variable as parameter to constructor c#
pass a variable as parameter to constructor as i want to change the variable value with changeable value

i'm new to c# so that i tries to implement one thing in many way i did what i want to do with using ( function ) and worked

```<code>namespace testConstructors
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static void Persons(string DepartmentName)
        {
          System.Windows.Forms.MessageBox.Show("Your Department is " + DepartmentName + " Fixed salary = 1500");
        }

        private void btnShowTotalSalary_Click(object sender, EventArgs e)
        {
            int fixedSalary = 1500;
            if (rbtHR.Checked)
            {
                lblTotalSalary.Text= Convert.ToString(fixedSalary + 200);
                Persons("HR");
            }
            if (rbtDevelopers.Checked)
            {
                lblTotalSalary.Text= Convert.ToString(fixedSalary + 8000);
                Persons("developer");
            }
            if (rbtTesters.Checked)
            {
                lblTotalSalary.Text = Convert.ToString(fixedSalary + 2);
                Persons("tester");
            }
        }

        private void rbtHR_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}
</code>```

but when i want to use to classes and take one class and add aconstructor to it and pass the value through it as this code shown ,it worked but not changed in everey time change the radio button as first code did .

so i want to know is this thing can be done by constructor or not

```<code>namespace testConstructors
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnShowTotalSalary_Click(object sender, EventArgs e)
        {
            string DeptName;
            Persons p2 = new Persons("HR");
            if (rbtHR.Checked)
            {
                lblTotalSalary.Text= Convert.ToString(p2.fixedSalary + 200);
                DeptName = "HR";
            }
            if (rbtDevelopers.Checked)
            {
                lblTotalSalary.Text= Convert.ToString(p2.fixedSalary + 8000);
                DeptName = "Developers";
            }
            if (rbtTesters.Checked)
            {
                lblTotalSalary.Text = Convert.ToString(p2.fixedSalary + 2);
                DeptName = "Testers";
            }
        }

        private void rbtHR_CheckedChanged(object sender, EventArgs e)
        {

        }
    }

    class Persons
    {
        public int fixedSalary;
        public Persons(string DepartmentName)
        {
            fixedSalary = 1500;
            System.Windows.Forms.MessageBox.Show("Your Department is " + DepartmentName + " Fixed salary = 1500");
        }
    }
}
</code>```

答:
Instead of passing hardcoded department name to the constructor of Person class, pass the initialized DeptName variable to Person class.

```<code>    private void btnShowTotalSalary_Click(object sender, String e)
    {
        string DeptName = "Department";

        if (rbtHR.Checked)
        {
            lblTotalSalary.Text= Convert.ToString(p2.fixedSalary + 200);
            DeptName = "HR";
        }
        if (rbtDevelopers.Checked)
        {
            lblTotalSalary.Text= Convert.ToString(p2.fixedSalary);
            DeptName = "Developers";
        }
        if (rbtTesters.Checked)
        {
            lblTotalSalary.Text = Convert.ToString(p2.fixedSalary + 2);
            DeptName = "Testers";
        }

        Person p2 = new Person(DeptName);
    }
</code>```

Body:
Instead of passing hardcoded department name to the constructor of Person class, pass the initialized DeptName variable to Person class.

    private void btnShowTotalSalary_Click(object sender, String e)
    {
        string DeptName = "Department";

        if (rbtHR.Checked)
        {
            lblTotalSalary.Text= Convert.ToString(p2.fixedSalary + 200);
            DeptName = "HR";
        }
        if (rbtDevelopers.Checked)
        {
            lblTotalSalary.Text= Convert.ToString(p2.fixedSalary);
            DeptName = "Developers";
        }
        if (rbtTesters.Checked)
        {
            lblTotalSalary.Text = Convert.ToString(p2.fixedSalary + 2);
            DeptName = "Testers";
        }

        Person p2 = new Person(DeptName);
    }


问:
Design Pattern for Filtering
I have a requirement where I get a list of objects say List.

Now I have filter Criteria which I need to apply to filter out the objects in the list.

Currently I am thinking of using chain of responsibility.

So my criteria could be say,
Blacklisted names, whitelisted names etc..
So if an object contains name which is blacklisted I need to remove it from the final list.

Please suggest which pattern is suitable for this problem.

答:
At this very phase of development you describe, I wouldn't recommend looking for a certain pattern and implement it. Just as a first step, collect what you know:

You need to filter

You know certain criteria

You have an object list of type List

You would like to have (I assume) a new listFiltered of the same Type List.

Now it depends what libraries and what language you work with. One could think of a finished library method that takes a list of type List and applies a user defined filter function to return a filtered copy. Or maybe there is a special kind of iterator (or cursor) available that takes a filter argument, iterates and returns only the suitable items by skipping the not suitable ones.

So my second step I recommend is looking if somebody has solved the same problem, by using a library function or maybe she/he has noted a snippet. Also, it could be that you solved a similar problem earlier. It could be useful to adopt what you have written earlier.

If you don't find anything like this, then my recommendation as third step would be to implement straightforward what you need. It could look like this (all code is pseudocode):

```<code>class MyTools {
    ...
    List filterList(list, filterCriteria) ...
    ...
}
</code>```

or:

```<code>class ListHelper {
    ...
    List filter(list, filterCriteria) ...
    ...
}
</code>```

Some draft discussion base for the filter function (pseudocode):

```<code>List filter(list, criteria) {

    List result = new List();
    foreach (item in list) {
       if (this.criteriaMatches(item, criteria)) {
          result.add(item);
       }
    }

    return result;
 }
</code>```

By drafting that way, you'll learn that you need some "criteriaMatches()" method, and you will realize that you should think about referencing or cloning, and possibly deep or shallow cloning, and how to test the whole bunch, and if some code should be synchronized, etc. These are the relevant questions now.

According to my experience, you cannot save time by "predicting" the right pattern, because reality and also code development is too chaotic. It is better to be prepared to constantly adjust and refactor the code structure in a well ordered and alert manner.

So, later it could be that you would migrate your code written today into a final Tools-Class. Or it could be that you will drop it and write a special iterator, because your team would benefit from doing so. Only the larger perspective will make clear what pattern really is useful, maybe decided by your team.

Finally, the "chain of responsibility" as you mentioned, is a pattern in that a list of acting objects can be enhanced by adding new objects. An argument to work is fed into the list, and the suitable object in the list will decide: "This object is my responsibility, I'll work this object." You could try to think around ten corners to see such a chain in a simple filter. But this will produce more work later than just straightforward implementing the solution. For the task described, it is an overhead.

Title: Design Pattern for Filtering

Body:
At this very phase of development you describe, I wouldn't recommend looking for a certain pattern and implement it. Just as a first step, collect what you know:

You need to filter

You know certain criteria

You have an object list of type List

You would like to have (I assume) a new listFiltered of the same Type List.

Now it depends what libraries and what language you work with. One could think of a finished library method that takes a list of type List and applies a user defined filter function to return a filtered copy. Or maybe there is a special kind of iterator (or cursor) available that takes a filter argument, iterates and returns only the suitable items by skipping the not suitable ones.

So my second step I recommend is looking if somebody has solved the same problem, by using a library function or maybe she/he has noted a snippet. Also, it could be that you solved a similar problem earlier. It could be useful to adopt what you have written earlier.

If you don't find anything like this, then my recommendation as third step would be to implement straightforward what you need. It could look like this (all code is pseudocode):

class MyTools {
    ...
    List filterList(list, filterCriteria) ...
    ...
}

or:

class ListHelper {
    ...
    List filter(list, filterCriteria) ...
    ...
}

Some draft discussion base for the filter function (pseudocode):

List filter(list, criteria) {

    List result = new List();
    foreach (item in list) {
       if (this.criteriaMatches(item, criteria)) {
          result.add(item);
       }
    }

    return result;
 }

By drafting that way, you'll learn that you need some "criteriaMatches()" method, and you will realize that you should think about referencing or cloning, and possibly deep or shallow cloning, and how to test the whole bunch, and if some code should be synchronized, etc. These are the relevant questions now.

According to my experience, you cannot save time by "predicting" the right pattern, because reality and also code development is too chaotic. It is better to be prepared to constantly adjust and refactor the code structure in a well ordered and alert manner.

So, later it could be that you would migrate your code written today into a final Tools-Class. Or it could be that you will drop it and write a special iterator, because your team would benefit from doing so. Only the larger perspective will make clear what pattern really is useful, maybe decided by your team.

Finally, the "chain of responsibility" as you mentioned, is a pattern in that a list of acting objects can be enhanced by adding new objects. An argument to work is fed into the list, and the suitable object in the list will decide: "This object is my responsibility, I'll work this object." You could try to think around ten corners to see such a chain in a simple filter. But this will produce more work later than just straightforward implementing the solution. For the task described, it is an overhead.


问:
How do you unit-test code using graph structures?
I am writing (recursive) code that is navigating a dependency graph looks for cycles or contradictions in the dependencies. However, I am not sure how to approach unit testing this. The problem is that one of our main concerns is will the code handle on all the interesting graph structures that can arise and making sure that all nodes will be handled appropriately.

While usually 100% line or branch coverage is sufficient to be confident that some code works, it feels like even with 100% path coverage you'd still have doubts.

So, how does one go about selecting graph structures for test cases to have confidence that their code could handle all the conceivable permutations you'll find in real world data.

PS- If it matters, all edges in my graph are labelled "must have" xor "cannot have" and there are no trivial cycles, and there is only one edge between any two nodes.

PPS- This additional problem statement was originally posted by the question's author in a comment below:

For all vertices N in forest F, for all vertices M, in F, such that if there are any walks between N and M they all must either use only edges labelled 'conflict' or 'requires'.

答:
No testing whatsoever is going to be able to be sufficient in this case, not even tons of real world data or fuzzing. A 100% code coverage, or even 100% path coverage is insufficient to test recursive functions.

Either the recursive function stands up to a formal proof (shouldn't be that difficult in this case), or it doesn't. If the code is too intertwined with application specific code to rule out side effects, that's where to start.

The algorithm itself sounds like a simple flooding algorithm, similar to a simple broad first search, with the addition of a blacklist which must not intersect with the list of visited nodes, run from all nodes.

```<code>foreach nodes as node
    foreach nodes as tmp
        tmp.status = unmarked

    tovisit = []
    tovisit.push(node)
    node.status = required

    while |tovisit| > 0 do
        next = tovisit.pop()
        foreach next.requires as requirement
            if requirement.status = unmarked
                tovisit.push(requirement)
                requirement.status = required
            else if requirement.status = blacklisted
                return false
        foreach next.collides as collision
            if collision.status = unmarked
                requirement.status = blacklisted
            else if requirement.status = required
                return false
return true
</code>```

This iterative algorithm fulfills the condition that no dependency may be required and blacklisted at the same time, for graphs of arbitrary structure, starting from any arbitrary artifact whereby the starting artifact is always required.

While it may or may not be as fast as your own implementation, it can be proven that it terminates for all cases (as for each iteration of the outer loop each element can only be pushed once onto the tovisit queue), it floods the entire reachable graph (inductive proof), and it detects all cases where an artifact is required to be required and blacklisted simultaneously, starting from each node.

If you can show that your own implementation has the same characteristics, you can prove correctness without resulting to unit testing. Only the basic methods for pushing and popping from queues, counting queue length, iterating over properties and alike need to be tested and shown to be free of side effects.

EDIT: What this algorithm does not prove, is your graph being free of cycles. Directed acyclic graphs are a well researched topic though, so finding a ready made algorithm to prove this property should be easy as well.

As you can see, there is no need to reinvent the wheel, at all.

Body:
No testing whatsoever is going to be able to be sufficient in this case, not even tons of real world data or fuzzing. A 100% code coverage, or even 100% path coverage is insufficient to test recursive functions.

Either the recursive function stands up to a formal proof (shouldn't be that difficult in this case), or it doesn't. If the code is too intertwined with application specific code to rule out side effects, that's where to start.

The algorithm itself sounds like a simple flooding algorithm, similar to a simple broad first search, with the addition of a blacklist which must not intersect with the list of visited nodes, run from all nodes.

foreach nodes as node
    foreach nodes as tmp
        tmp.status = unmarked

    tovisit = []
    tovisit.push(node)
    node.status = required

    while |tovisit| > 0 do
        next = tovisit.pop()
        foreach next.requires as requirement
            if requirement.status = unmarked
                tovisit.push(requirement)
                requirement.status = required
            else if requirement.status = blacklisted
                return false
        foreach next.collides as collision
            if collision.status = unmarked
                requirement.status = blacklisted
            else if requirement.status = required
                return false
return true

This iterative algorithm fulfills the condition that no dependency may be required and blacklisted at the same time, for graphs of arbitrary structure, starting from any arbitrary artifact whereby the starting artifact is always required.

While it may or may not be as fast as your own implementation, it can be proven that it terminates for all cases (as for each iteration of the outer loop each element can only be pushed once onto the tovisit queue), it floods the entire reachable graph (inductive proof), and it detects all cases where an artifact is required to be required and blacklisted simultaneously, starting from each node.

If you can show that your own implementation has the same characteristics, you can prove correctness without resulting to unit testing. Only the basic methods for pushing and popping from queues, counting queue length, iterating over properties and alike need to be tested and shown to be free of side effects.

EDIT: What this algorithm does not prove, is your graph being free of cycles. Directed acyclic graphs are a well researched topic though, so finding a ready made algorithm to prove this property should be easy as well.

As you can see, there is no need to reinvent the wheel, at all.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: Oh. Type hinting for primitives. That would be nice.</p>

OwnerDisplayName: ruurd


问:
Why is String immutable in Java?
I couldn't understand the reason of it. I always use String class like other developers, but when I modify the value of it, new instance of String created.

What might be the reason of immutability for String class in Java?

I know there are some alternatives like StringBuffer or StringBuilder. It's just curiosity.

答:
In general, you will encounter value types and reference types. With a value type, you don't care about the object that represents it, you care about the value. If I give you a value, you expect that value to stay the same. You don't want it to change suddenly. The number 5 is a value. You don't expect it to change to 6 suddenly. The string "Hello" is a value. You don't expect it to change to "P*** off" suddenly.

With reference types you care about the object, and you expect it to change. For example, you will often expect an array to change. If I give you an array, and you want to keep it exactly as it is, you either have to trust me not to change it, or you make a copy of it.

With the Java string class, the designers had to make a decision: Is it better if strings behave like a value type, or should they behave like a reference type? In the case of Java strings, the decision was made that they should be value types, which means since they are objects, they must be immutable objects.

The opposite decision could have been made, but in my opinion would have caused lots of headaches. As said elsewhere, many languages made the same decision and came to the same conclusion. An exception is C++, which has one string class, and strings can be constant or non-constant, but in C++, unlike Java, object parameters can be passed as values, and not as references.

Title: Why is String immutable in Java?


问:
Slicing up the Development Stack - diagonally?
We've got a new project going on, and at the moment developers have been split into two teams, team A and team B. This project has 2 parts to it which require development throughout the development stack. Very simplified sample of our stack shown below:

Each part of the project requires development across the entire stack, so I would typically expect a full stack developer approach which is how we have been breaking down our work within team B, designing and working out the interactions between different parts.

I've recently learnt however, that team A want to be in charge of certain parts of the stack, and they are proposing a divide between the two teams, where the Data Abstraction Layer (and putting content in the Data layer) is handled by themselves with no development from Team B. The divide would look something akin to this:

To me this feels very un-natural. Each team has different distinct objectives and timescales to achieve these on, but Team B will have a dependency on Team A to implement features. The proposed solution is that common interfaces are defined up-front (there is probably a 2 year timescale on the project so they could be numerous). Team A will then develop the required bits to these interfaces early on despite having their own set of goals, while Team B stub out all calls for the immediate short term so they can progress.

I have concerns about this approach regarding:

Interfaces may change and Team A may not have the bandwidth or time
to accommodate changing requirements.

Bugs in Team A's code could prevent Team B progressing, and again they may not be the priority to fix these due to Team A having a different prioritization queue.

Lack of knowledge spread across the teams - Team B may not fully understand what goes on under the hood and may make poor design decisions because of this.

It has been suggested that many companies in the industry have sub-teams and must be able to handle this. From my understanding, generally teams are either split how I initially expected (Full Stack) or by breaking up the technology stack like below:

So I'm interested in knowing what the rest of industry is doing. Are most splits vertical/horizontal? Does a diagonal split make sense? If a diagonal split were to occur do my concerns seem valid and is there anything else Team B should be concerned about? To note I'm probably going to be held responsible for the success or failure of Team B.

答:
Your concerns are extremely valid. Especially the first two points about Team A not having the time to add features or fix bugs that impact Team B. I've seen this happen at my own job quite a few times.

This might be a good idea if:

It is known that Team A will be working on the projects that require new features in the database, while Team B's goal is essentially to do "only frontend" features. For instance, if Team B is writing your company's new iPhone app, it's likely that they will not be adding new database fields for a while, as they need to port/reimplement all the features of the desktop version.

The "full stack" has become sufficiently complex that no single dev (or dev team) can effectively "own" the entire thing. By "own" I mean not just add features and fix bugs, but understand and care about the whole system to the point that they can avoid adding more technical debt to it over time. In this case, the "diagonal" split is the sensible move if Team A owns a UI/Web API that's either extremely simple or unavoidably tightly-coupled to the DAL/database implementation (perhaps some internal diagnostic tools?), while Team B does all the complicated user-facing frontend stuff.

Management understands the risk of Team A becoming a bottleneck, and would be willing to de-diagonalize things if or when this risk turns into a real problem.

I can't speak to what is more or less common in the industry, but at least where I work, there is a clear need for all application developers to be "full stack". What we do have are "infrastructure" teams that develop/maintain our in-house database, our web service framework and our UI framework (did I mention my company is huge?), so that all of our hundreds of applications can have full stack devs while the company as a whole can still provide consistent performance and UI to all of our services.

Recently our company has been making a brand new UI framework, so there was a period when some of our new apps were quite badly blocked on bugs and missing features in the new framework. This is no longer the case, mostly because some of us were given permission to submit pull requests to the team that owns the framework (not quite "de-diagonalization", but you get the idea).


答:
Once upon a time high level languages were just an idea. People tried to implement compilers. Back then there were severe hardware limitations - there were no graphical tools so "plain text" ended up being used for the input file format; computers typically had an extremely tiny amount of RAM so the source code had to be broken into pieces and the compiler got split into separate utilities (pre-processor, compiler, assembler, linker); CPUs were slow and expensive so you couldn't do expensive optimisations, etc.

Of course with many source files and many utilities being used to create many object files, it's a mess to build anything manually. As a work-around for the design flaws in the tools (caused by severely limited hardware) people naturally started writing scripts to remove some of the hassle.

Sadly, scripts were awkward and messy. To work around the problems with scripts (which were a work-around for the design flaws in the tools caused by limited hardware) eventually people invented utilities to make things easier, like make.

However; makefiles are awkward and messy. To work around the problems with makefiles (which were a work-around for a work-around for the design flaws in the tools caused by limited hardware) people started experimenting with auto-generated makefiles; starting with things like getting the compiler to generate dependencies; and leading up to tools like auto-conf and cmake.

This is where we are now: work-arounds for a work-arounds for a work-around for the design flaws in the tools caused by limited hardware.

It's my expectation that by the end of the century there'll be a few more layers of "work-arounds for work-arounds" on top of the existing pile. Ironically, the severe hardware limitations that caused all of this disappeared many decades ago and the only reason we're still using such an archaic mess now is "this is how it's always been done".


答:
Is make really outdated?

I don't think so. In the end, make is still powerful enough to provide all the functionality desired, like conditional compilation of changed source and alike. Saying make was outdated, would be the same as saying writing custom linker scripts was outdated.

But what raw make doesn't provide, are extended functionalities and stock libraries for comfort, such as parametric header generation, integrated test framework, or even just conditional libraries in general.

On the other hand, CMake is directly tailored towards generating generic ELF libraries and executables. Whenever you depart from them predefined procedures, you have to start hacking CMake just as you used to hack your own Makefiles.

Considering that you can create far more in C++ than just your average application for an system which knows ELF loaders, CMake surely isn't suited for all scenarios. However if you are working in such a standardized environment, CMake or any other of these modern script generator frameworks certainly are your best friends.

It always depends on how specialized your application is, and how well the structure of the CMake framework fits your work flow.


问:
Does Go implicitly discourage getters and setters and encourage direct member access?
As the title says, is accessing public struct fields more idiomatic in Go than getters and setters? Wouldn't that lead to violation of data encapsulation, also public fields in other OO languages like Java are frowned upon.

This answer even claim that getters and setters are not idiomatic in Go.

Does the use of struct keyword (instead of class) mean that it is meant to be used like C-style structs (POD)?

答:
The Effective Go article on the official website mentions getters and setters are fine, and even has guidelines on how to name them:

Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

```<code>owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}
</code>```

Private fields and public getters are useful for guaranteeing invariants of objects since you can prevent people from poking the object's internals.

Since setters perform mutations, you should obviously be careful. Mutations don't play well with aliasing because a mutation in one place can effect code somewhere else, and this is especially important in concurrent settings which are widespread in Go.

Also, values are often implicitly copied in Go (similar to structs in C and C#), so a setter call that is expected to have an effect in some place may not have that effect, which is another reason to be careful when dealing with setters.

Body:
The Effective Go article on the official website mentions getters and setters are fine, and even has guidelines on how to name them:

Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

Private fields and public getters are useful for guaranteeing invariants of objects since you can prevent people from poking the object's internals.

Since setters perform mutations, you should obviously be careful. Mutations don't play well with aliasing because a mutation in one place can effect code somewhere else, and this is especially important in concurrent settings which are widespread in Go.

Also, values are often implicitly copied in Go (similar to structs in C and C#), so a setter call that is expected to have an effect in some place may not have that effect, which is another reason to be careful when dealing with setters.


问:
Clarification on MVC Architecture Overview
I'm doing an MVC 4 architecture diagram for a report and since I'm relatively new to MVC,i was wondering could some one clarify with me is REST (HTTPPOST etc) between view and controller, or controller to model? also should model drawn as in the server side and view + controller on client side?

here a few of my mock ups atm

答:
You're almost there...

Putting the REST between the view and the controller would be the right choice. That means that your view, i.e. a javascript code, will send REST calls to your server, which process those calls in the appropriate controller (then the models and etc.). In addition this controller would be responsible for the response back to the client.

I believe you have a confusion with the controller's part in the system. Depending on your implementation and application frameworks you're using, the controller should be part of your 'server' layer, which tells which and what view to call/dispatch.

Take a look at the following (simple) diagram:

The controller is responsible for updating the view, and maybe showing you another view.
For example, consider the following scenario:

The user fills out a form and submits it

Server validates the form and

2.1. If it is valid - the controller will route you to a "thank you" view

2.2. else the controller will route you to a "missing input" view

The user gets the routed view as a response.


问:
How can I argue convincingly against duplicating database columns?
I've started working at a new organization and one of the patterns I've been seeing in the database is duplicating fields to make writing queries easier for the business analysts. We're using Django and its ORM.

In one case, we keep a MedicalRecordNumber object with a unique string identifying a patient in a certain context. We have Registration objects which track patients and have associated MedicalRecordNumbers, but rather than using a foreign key relationship, they duplicate the string so they can avoid writing a join (not for performance reasons). This pattern is common throughout the database.

For me the importance of a data model being clean is just so I can think about it well. Needless complexity is a waste of my limited cognitive processing time. It's a systematic problem. Not being comfortable writing joins is a rectifiable skills issue. I don't necessarily want to advocate going back and changing the schema, but I'd love to be able to convincingly articulate the problems with this type of duplication.

答:
I think the strongest argument for data normalization for business analysts is that it promotes data integrity. If your key data is stored in only one place (one column, in one table), it's much less likely that the data will get corrupted by incorrect updates. I think they would probably care about the importance of data integrity, so this this might be a good way to convince them to update their ways of interacting with the database.

A slightly more difficult method of querying is likely going to be preferable to potential data corruption.


问:
Calculating disk capacity and max data transfer rate of a hard drive?
I am learning about hard drive concepts and I came across this question:

Suppose we have a 10000 RPM disk has 8 heads and 480 cylinders. It is divided into 120-  cylinder zones with the cylinders in different zones containing 200, 240, 280, and 320 sectors. As- sume each sector contains 4096 bytes and a seek time between adjacent cylinders of 2 msec.

what is the disk capacity?

What is the maximum transfer rate?

For the first question, I started off with these steps

Add the sectors together for a 120 cylinder zone: (200+240+280+320) = 1040 sectors

Since there are 4 cylinder zones, there are a total of 4160 sectors.

Multiply the sectors by 4096: 4160 * 4096 bytes = 17.03 MB

That seems incredibly small. Is this correct?

For problem 2, I am not sure where to start.

答:
To get the capacity of the disk, multiply the total number of sectors by the sector size.  The total number of sectors is 120*200 + 120*240 + 120*280 + 120*320 or 124800, so the total disk capacity should be 124800 * 4096, or 511,180,800 bytes.

To get the transfer rate, first, pick the cylinder zone with the largest number of sectors (320).  This is the cylinder zone that will yield the greatest transfer rate.  It's probably near the outside of the disk (since there's more surface area to work with).

Now, multiply the number of sectors by the number of bytes per sector (320 * 4096) and you get 1310720.  This is the number of bytes you can retrieve per disk rotation.

The number of rotations per second is 10000/60, approximately 166.67.  Multiply that by 1310720 bytes per rotation, and you get 218453333, or about 208 megabytes per second.

Since you need 166.67 cylinders to get a full second's worth of data, you should subtract the amount of data that cannot be read while the head is seeking between cylinders (2 ms per seek).


答:
Make strings object like, with built in methods to replace the inconsistently named and parametered non-object ones. e.g.

```<code>$subject->replace($search,$replace);
$string->split($separator);
$string->trim();
</code>```

etc.

Edit: one more thing: These methods should always expect and emit UTF-8, except for ones specifically intended to deal with encodings. If input is invalid UTF-8, an exception should be thrown, even if the output of the function wouldn't be affected by the encoding.

Body:
Make strings object like, with built in methods to replace the inconsistently named and parametered non-object ones. e.g.

$subject->replace($search,$replace);
$string->split($separator);
$string->trim();

etc.

Edit: one more thing: These methods should always expect and emit UTF-8, except for ones specifically intended to deal with encodings. If input is invalid UTF-8, an exception should be thrown, even if the output of the function wouldn't be affected by the encoding.


答:
I understand, why somebody wants to avoid writing a join for each select.

But you can create once a view with the join and use it instead of your unnormalized table.

So you combine the advantage of normalization with the convenience of an easy select.

Title: How can I argue convincingly against duplicating database columns?

Body:
I've started working at a new organization and one of the patterns I've been seeing in the database is duplicating fields to make writing queries easier for the business analysts. We're using Django and its ORM.

In one case, we keep a MedicalRecordNumber object with a unique string identifying a patient in a certain context. We have Registration objects which track patients and have associated MedicalRecordNumbers, but rather than using a foreign key relationship, they duplicate the string so they can avoid writing a join (not for performance reasons). This pattern is common throughout the database.

For me the importance of a data model being clean is just so I can think about it well. Needless complexity is a waste of my limited cognitive processing time. It's a systematic problem. Not being comfortable writing joins is a rectifiable skills issue. I don't necessarily want to advocate going back and changing the schema, but I'd love to be able to convincingly articulate the problems with this type of duplication.


答:
Thinking of it in terms of tradeoffs rather than good/bad will be more productive. They are trading off advantages of normalization (esp. consistency) for advantages in query usability.

At one extreme, the database would become useless if the data got severely inconsistent. At the other extreme, the database would be useless if it's too difficult for the people who need to query it every day to get results they can count on.

What can you do to reduce the risks and the costs?

Build a consistency checker tool and run it regularly.

Route write access through software that updates the replicated data consistently.

Add views or build query tools that do the joins automatically so the business people can think in terms of the information rather than the DB internals.


答:
Your operational database should be highly normalized, to reduce anomalies.

Your analytic database (warehouse) should be highly denormalized, to ease analysis.

If you don't have a separate analytic database, you should make some highly denormalized [materialized] views.

If you tell your senior business analysts / managers to do lots of joins for a simple analysis, well, you might get fired.

Agile Data Warehouse Design is a good book

See my quick n' dirty data warehouse tips here


问:
Clustering algorithm
I have a set of n elements (1,000 <= n <= 100,000) and I can compute the grade of similarity between each pair, that is a value from 0 (very similar) to 1 (very different). I would like to cluster the elements based on their grade of similarity.

I thought about representing them as a graph, the elements are the vertices and the weighted edges are the similarity between them. I read about the MCL algorithm but I think it isn't the best approach since my graph is complete.

On the other hand, as there are a lot of elements, maybe computing the similarity between each pair is not the best practice (I want a fast algorithm). I also read something about leader clustering algorithms but, again, I am not sure if it is the best approach because, as far as I know, it is quite prone to fail due to its greediness (I would like something more robust).

Edit: I forgot to mention that I know a threshold for which when the comparison between two elements is higher than it, then I know that they belong to different clusters.

答:
I don't think any meaningful clustering is possible if similarity(a,b) and similarity(b,c) don't upper-bound similarity(a,c). To demonstrate, let's consider the following simple (and extreme) example with only 3 items:

similarity(a,b) == 0

similarity(b,c) == 0

similarity(a,c) == 1

a should thus be in the same cluster as b and b in the same cluster as c. But a and c should be in different clusters, which contradicts the previous expectations.

Title: Clustering algorithm


问:
"One of some"-type
Say that you have some different classes that does not really have any functionality in common, but somewhere in your program, you need one of them (which one is not necessarily important) because they have a functionality in that context. What is the best way to do that?

I know that you can take an Object and use instanceof to check whether it is one of those types, but I am looking for a way to let the type system ensure that it will just be one of those types. Or is that impractical/impossible?

What I thought about doing was to create an empty interface and implement it in all the classes that needed it. but I have seen that you are supposed to use annotations instead of a marker interface, but I am not sure if that applies in this situation because I do not really care about run-time information. Another thing I am worried about is that implementing that interface in those classes will cause spaghetti code. Those classes should not really have to know anything about how they are used elsewhere.

答: Well, all objects extend from the Object class, so maybe you could try to create a generic class and pass in as parameters each of the types. But I am not sure how or why they would all be related because as you said, they have nothing to do with each other. Interesting.</p>

Title: "One of some"-type


答:
This is a spectral clustering problem which has been studied in research area for a long time. Generally speaking, a spectral clustering algorithm uses the eigenvalues (aka spectrum) analysis to split the data into two or more clusters at a time. Each of this splitting is somehow globally optimized which leads to a overall good results of the final clustering.

The wikipedia entry can give more details.

PS: Commonly an element of a similarity matrix, which is a similarity measure for two objects, has a smaller value for dissimilar objects and a larger value for similar ones.

Title: Clustering algorithm

Body:
I have a set of n elements (1,000 <= n <= 100,000) and I can compute the grade of similarity between each pair, that is a value from 0 (very similar) to 1 (very different). I would like to cluster the elements based on their grade of similarity.

I thought about representing them as a graph, the elements are the vertices and the weighted edges are the similarity between them. I read about the MCL algorithm but I think it isn't the best approach since my graph is complete.

On the other hand, as there are a lot of elements, maybe computing the similarity between each pair is not the best practice (I want a fast algorithm). I also read something about leader clustering algorithms but, again, I am not sure if it is the best approach because, as far as I know, it is quite prone to fail due to its greediness (I would like something more robust).

Edit: I forgot to mention that I know a threshold for which when the comparison between two elements is higher than it, then I know that they belong to different clusters.


问:
Agile: How to deal with bottle neck approvals outside of SCRUM?
Is there an Agile term for when there is a stakeholder that acts as a bottleneck by jumping in only occasionally to trump decisions made collectively by the team? (ie, upper management who never partake in the process, but will occasionally review work and decide they don't like it)? I'm familiar with Pig and Chickens. Would this simply be a 'type of chicken'?

Is there any Agile technique to deal with said type of person? Is there a particular role on the Agile team that should be in charge of managing this type of issue?

An example might be that the product owner is happy, IT is happy, UX is happy, various business roles are happy, and sprints are underway, but suddenly someone's boss's boss has decided they want everything put into a PPT deck for them to 'approve' where we're at.

答:
More examples of interruptions will be helpful to understand the reasoning why your skip manager or another stakeholder requires "stop everything and do this" type of work.

For "put a PPT together to approve", could this be the lack of transparency up?

Does your team invite all the stakeholders to attend the demos showing the status/progress of sprint's deliverables?

What's the outcome of your planning sessions? Is it something that only your team owns? Do you communicate the stories and priorities you've agreed on to your top management (Is this information easily accessible/discoverable?)

I do agree with Steven, if the mid-sprint change is driven by a business need or is the result of a micro-management are two different cases.

When business requires changing the direction - that's the whole reason you do agile then. If that's the case and you think it happens quite often, consider shortening your iterations or going full-blown Kanban instead?

If that's a micromanagement issue, protect your team, communicate the ground rules to your management - once the planning is done, no new work can be injected into sprint - it will have to wait until the next sprint. Usually, if the iterations are short - a week long - hardly anyone objects waiting a week max if they have a request. Back it up with data - showing how velocity suffers when sprints are interrupted, explaining how context switching is wasteful, etc.


问:
Ambiguity of seemingly clear method names in APIs
(The question is language-agnostic, but to illustrate the point, I wrote the examples in C#.)

Say I'm trying to model the behavior of "components" that communicate via "ports".

I might model this as:

```<code>public interface Component
{
    int  Read(int portID, byte[] buffer);
    int Write(int portID, byte[] buffer);
}
</code>```

and perhaps implement the interface as:

```<code>public class MyComponent : Component
{
    private class Port
    {
        int  Read(byte[] buffer) { ... }
        int Write(byte[] buffer) { ... }
        void DoSomethingComplex()
        {
            this.Read(...);
            // ...
            this.Write(...);
        }
    }
    private Dictionary<int, Port> ports;
    public override int  Read(int portID, byte[] buffer) { ports[portId]. Read(buffer); }
    public override int Write(int portID, byte[] buffer) { ports[portId].Write(buffer); }
}
</code>```

Simple enough, but consider what you would expect Read and Write to do:

From the perspective of an outsider, it seems natural for Read to read data from the port of the component into the given buffer.
However, as an insider who is calling this.Read(...), is that really what you expect?
Or would you expect the data to be read from the buffer into the port?

My question is twofold:

Given no additional documentation, which meaning of Read and Write is more intuitive?

How can I reasonably clearly name these functions so that the intent is clear without the need for additional documentation?

(Obviously, I can name them ReadFromPortIntoBuffer and WriteToPortFromBuffer or something like that, but one hopes for more succinct names.)

答:
Naming things is hard. But in my experience, ambiguity like this can almost always be solved by using a slightly more verbose name in the right place. The alternative method names you suggested are indeed ugly; in this example my first choice would be to rename the parameters:

```<code>public interface Component
{
    int  Read(int portID, byte[] outputBuffer);
    int Write(int portID, byte[] inputBuffer);
}
</code>```

Though as @rwong pointed out, if this particular example is real code, the goal should be to resemble a standard C# Stream as much as possible.

As for which "direction" is more intuitive for Read/Write, I don't believe either one is. In fact, my personal preference would be a Read method that returns the stuff it just read, and no "output parameters" in either method (imo those are just an ugly workaround for the lack of efficient/complex/multiple return values in many languages). I'm sure you could find loads of people who would assert that reading to or reading from are the "obvious" default meanings, depending on what Streams/Readers/Writers/languages they're most familiar with.

Body:
Naming things is hard. But in my experience, ambiguity like this can almost always be solved by using a slightly more verbose name in the right place. The alternative method names you suggested are indeed ugly; in this example my first choice would be to rename the parameters:

public interface Component
{
    int  Read(int portID, byte[] outputBuffer);
    int Write(int portID, byte[] inputBuffer);
}

Though as @rwong pointed out, if this particular example is real code, the goal should be to resemble a standard C# Stream as much as possible.

As for which "direction" is more intuitive for Read/Write, I don't believe either one is. In fact, my personal preference would be a Read method that returns the stuff it just read, and no "output parameters" in either method (imo those are just an ugly workaround for the lack of efficient/complex/multiple return values in many languages). I'm sure you could find loads of people who would assert that reading to or reading from are the "obvious" default meanings, depending on what Streams/Readers/Writers/languages they're most familiar with.


答:
The answers which have already been upvoted pretty much cover the "how to avoid duplication" (using views) but not the why.  They basically show that duplication of columns is the wrong solution to the problem of making it easier to write queries.  But the question "why not duplicate any random column just for the heck of it?" still stands.

The answer is "Because of Murphy's Law".  Murphy's law states that:

If something can go wrong, it will.

In this case, the contents of each row field of a duplicated column are supposed to be identical to the contents of each corresponding row field of the original column.  What can go wrong, is that the contents of some row fields may differ from the originals, wreaking havoc.  You might think that you have taken all conceivable precautions to ensure that they will not differ, but Murphy's law states that since they can differ, they will differ.  And havoc will ensue.

As an example of how this may happen, simply consider the fact that the duplicated columns don't get filled by magic; someone must actually write code which stores values in them whenever rows are created in the original table, and someone must write code which keeps updating them whenever the originals get modified.  Setting aside the fact that this is adding undue burden to code which enters data into the database, (and which is, by definition, far more crucial than any code which simply queries the database,) someone, somewhere, under certain circumstances, might forget to carry out this duplication.  Then, the values will differ.  Or they may remember to carry out the duplication, but not within a transaction, so it may, under certain rare fault conditions, be omitted.  But I did not really need to waste my time writing these examples, and you did not really need to waste your time reading them: the beauty of Murphy's Law is that it saves us from having to come up with examples of how something may go wrong on a case by case basis: if it can go wrong, it will.


答: An ini directive to E_ERROR on undefined constants, rather than assume it's a string with E_NOTICE.