问:
How does customized executable generation work?
One of the things that Valve's Steam distribution platform is known for is its Custom Executable Generation system, which creates a unique copy of a program for each person that buys it.

I'm sure that Valve isn't the only company or person to have implemented or thought of implementing such a system, however. If I wanted to try and roll my own system that generated executable files on the server side that are unique to the downloader or their account, what would I need to know how to do? What are the basics of such a system in the first place?

答:
Often you can implement the same functionality in lightly different ways.

Thts assume you have n functions for each you have have 2 different implementations (which are not to be the same assembly after compiling), than you can create
2ⁿ versions of your executable with the same functionality.

You can vary this aproach by changing the order of independent assembly commands, using more than 2 vaiands to choose between ...


问:
Is there any algorithm pattern to protect any content in the web to ensure I am the first one who created it?
A few years ago there was this hacker (don't remember who he was) that full disclosed a vulnerability in a given system, but to make sure nobody took credit for that, he created some kind of PGP key.

What I understood at the time is that he created a key to ensure he was the one who discovered it, but didn't disclosed who he was actually, just created some mechanism to be able to prove that he was the one who created the disclosure.

Ok. I get how algorithms and cryptography works. But I still don't understand how you can create a key to protect a given content disclosed in the web to prove you are the one who created it first! It is just words!

Is it really possible? What should be the process to ensure you can empirically prove it? Did I understood it correctly or I probably missed something regarding this case?

I hope this question is specific enough, basically it is just how to protect a content that you created in the web (a paragraph, a code, a word, etc.) and make sure you are the one who created it first, inside a given context.

With my knowledge I don't see how that is possible, but I am intrigued if there is a practical way to do it. Is there?

答:
You can do that quite easy. If you have a plaintext text, secret key S and public key P you do S(text) and get the cipher.

Now you can publish cipher and P but not S. Therefore, everyone can decrypt the cipher with P by doing P(cipher). If you now want to prove, that you are the one who created the cipher (and therefore the original text), you can either publish S, or - if you don't want anyone to know S - you can create another S("I was really the one who found the text first") and publish it. Because there is no way to create a cipher that is decrypted with P(cipher) that results in some meaningful text.

That is how you can prove it.

ContentLicense: CC BY-SA 3.0


问:
Is cloud computing just a way of renting resources?
The company I work at recently hosted a web service in Windows Azure and announced that. Now trade online magazines say lots of meaningless stuff like "company X moves to the cloud", "company X drops desktops for the cloud", etc.

Looks like there're lots of materials out there (starting with Wikipedia) that are very lengthy and talk a lot about "services" and "low entry price" and other stuff but I've read all that and don't see how they could be helpful for a layman in drawing a line between a service in a cloud and Stack Exchange that is also a service but is run on brick-and-mortar servers in a colocation.

Now from my experience with Windows Azure the real difference is the following. With a cloud the service owner rents hardware, network bandwidth and right to use the middleware (Windows 2008 that is used in Azure roles for example) on demand and also there's some maintenance assistance (like if the computer where a role is running crashes another computer is automatically found and the role is redeployed). Without a cloud the service owner will have to deal with all that on his own.

Will that be the right distinction?

答:
Cloud computing does not only provide resource renting.

It also offers a fault tolerance layer, should the rented resources fail. Serious cloud providers work hard to deliver a service without interruption.


答:
In days of old, scientists would publish anagrams of their work to be able to say "I thought of this idea." (look at the 'history' and 'establishment of priority' sections)  The thing is, they wanted to be able to take credit for it, but also give other scientists to publish their results if they had other ideas without building on the original idea.

For example Gallileo published SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS which was an anagram of altissimvm planetam tergeminvm obseravi which translated from Latin reads "I observed the highest planet in threefold shape".  He got it wrong - Saturn (the 'highest' planet known at the time) isn't built of three parts.  Fifty years later, Christiaan Huygens published AAAAAAA CCCCC D EEEEE H IIIIIII LLLL MM NNNNNNNNN OOOO PP Q RR S TTTTT UUUUU which in Latin is Annulo cingitur, tenui, plano, nusquam cohaerente, ad eclipticam inclinato which translates to "It is surrounded by a thin flat ring that does not touch it and is inclined against the ecliptic."

While those are historical bits now of interest, they show an important concept back then - providing a 'hash' that is easy to say "this hash encodes this text."  It is easy to go from the known text to the anagram or the hash, but hard to figure out what it is if you don't know what it is in the first place.

With the modern mechanisims, we have other ways of doing hashes.  Many of them are very closely related to cryptography.  There is the cryptographic hash function.  The idea being, still, it is easy to go from the text you know to the hash, but hard to go from the hash to the text you don't know.

And so, if you have a program you could publish a hash of the program that does something and then when you are ready to disclose it (possibly after the company fixes it or a period of time later), you can publish the actual code and everyone can see that, yes, this code matches that hash.

Title: Is there any algorithm pattern to protect any content in the web to ensure I am the first one who created it?

Body:
A few years ago there was this hacker (don't remember who he was) that full disclosed a vulnerability in a given system, but to make sure nobody took credit for that, he created some kind of PGP key.

What I understood at the time is that he created a key to ensure he was the one who discovered it, but didn't disclosed who he was actually, just created some mechanism to be able to prove that he was the one who created the disclosure.

Ok. I get how algorithms and cryptography works. But I still don't understand how you can create a key to protect a given content disclosed in the web to prove you are the one who created it first! It is just words!

Is it really possible? What should be the process to ensure you can empirically prove it? Did I understood it correctly or I probably missed something regarding this case?

I hope this question is specific enough, basically it is just how to protect a content that you created in the web (a paragraph, a code, a word, etc.) and make sure you are the one who created it first, inside a given context.

With my knowledge I don't see how that is possible, but I am intrigued if there is a practical way to do it. Is there?


问:
Approaches for manage AD users inside my HR system
I want to start a new HR web application based on asp.net mvc-5 & Entity Framework. as it is almost the case Users inside the HR system will exists inside the AD, and when a new user join our company we will create a new user inside the AD, then the HR dept will add the user to the HR system. but my question is how i can integrate my web application with AD users. i am thinking of the following approach:-

To create a table inside my system named ADUsers, with these fields; userID,FName,LName,Email .

to define a sync job which will run on daily basis, which will query all the AD users and populate the DB table accordingly. the sync job will add new users, delete removed users, update user info as defined inside the AD. In this case i can mange the users inside my system easier. for example i will have a module named Person , which should display all the Person AD Info (such as Fname, Lname,email address, etc) + their annual leave count, hire date, sick leave count which are HR specific  etc...

so can you advice on this approach please?

答:
You will probably need three tables:
User tables with a primary key and the usual first name, last name etc
Roles table with roles specific to your application (eg Administrator, Power User, User, read only)
UserRoles with the user primary key, roles primary key, date created, date last modified, enabled (NUMBER (1) default 1 with check constraint that this field can only have the values of 0 or 1

As you indicated you will also need a package/procedure to query Active Directory for the users who have roles that are of interest to your application.  The usual insert/update methods are required.  Keep in mind that you never want to delete a user for an intranet application if there is any logging so when someone leaves the user table is updated to indicate that enabled = 0.

You indicate that you are using SQL server, that makes it easier than some other databases.  A query such as this will get you started:

SELECT * FROM OpenQuery (    ADSI,     'SELECT displayName,
  telephoneNumber, mail, mobile, facsimileTelephoneNumber    FROM
  ''LDAP://DOMAIN.com/OU=Players,DC=DOMAIN,DC=com''    WHERE objectClass
  =  ''User''    ') AS tblADSI ORDORDER BY displayname

Keep in mind that there are many fields in Active Directory.  The less you ask for the better. Depending on how you access AD you may find a record limitation of no more than 1000 records can be returned.
Fields that you mention such as "annual leave count, hire date, sick leave count" should be in separate tables as the functionality is not connected to Active Directory

I don't know of any other practical way aside from a sync job.  Your system and AD are separate and you do not want to tie the two together closely.  Most AD data is best described as "Slowly changing" so a sync job on five minute intervals works for many applications.

1) You asked if this is valid approach to:

create a new DB table inside my system named ADUsers with these columns; UserID,Fname,Lname,Email address.

define a Sync job which will query the AD users and populate the ADUsers table accordingly

I have seen this approach taken in numerous windows web and client server systems

2) what do you mean by " Your system and AD are separate and you do not want to tie the two together closely"

you want to minimize the points of failure.  Your system should work when the sync process is not working due to unexpected failure.  Active Directory should work if your sync procedure fails.


问:
Is it misleading to label code as a particular design pattern if it only loosely fits the definition?
Background:

I have a rough, but working understanding of ~15 design patterns. It's been my experience using design patterns in my own projects that the resulting implementations usually end up as some variant of a pattern and don't always fit the canonical textbook examples.

Case:

I find it useful to leave tag-like comments that hint at an underlying archetype, e.g., in the following Javadoc class description, the "[Singleton]" label is used merely to describe that there's only one of these objects used at any given time. This class may or may not be set up to "restrict the instantiation of a class to one object" --Wikipedia.

```<code>/**
 * [Singleton]
 * The manager of all jewels, which are stored here in collections.
 */
public class JewelManager implements IDestroyable
{
</code>```

Context:

I'm working on a team with several other developers, but I need to assume there may be other devs working on the project with whom I will never have the opportunity to speak.

Question:

Is it misleading to label classes or methods as a particular design pattern (Strategy, Mediator, etc.) if they only loosely fit that definition?

答:
Labeling a pattern as [X] in Javadoc is really not so useful. Too many patterns are mis-applied because developers don't validate the patterns' assumptions (which are also not documented).

Your Singleton example is trivial, as Singleton is more of an idiom than a design pattern.

There's at least one project (http://www.jpatterns.org/) that uses Javadoc annotations for labeling elements of a design pattern in Java. See https://stackoverflow.com/q/127411/1168342

I'd argue that pattern application requires not just labels/annotations of the elements (the what), but also justifications with assumptions (the why).

Consider Visitor:

Labels should be applied to the classes in the Element hierarchy (Element at least) as well as the Visitor hierarchy (not so needed if you use the word Visitor in the pattern).

Assumptions (which could be documented in the Visitor interface, I suppose):

The Element hierarchy is expected not to evolve (else your Visitors will all need changing).

The Visitor hierarchy is expected to get new ConcreteVisitors in the future (which justifies the complexity of Visitor).

If you only have one ConcreteVisitor, then it could be hard to justify the complexity of double-dispatch (which affects performance and makes the code harder to debug). Most all design patterns are investments in complexity which should pay off if your assumptions are correct (e.g., Visitor is worth it if you need to add new functionality and your Element structure is stable). Break these assumptions and it may be a bad design finally.

Sadly, many of the wiki pages on patterns don't mention these strengths/weaknesses. Return to the GoF references or a good book on patterns for the details.


答:
A very simple way to establish that you are the first one to publish something, without revealing who you are immediately but having the option to do this later:

Publish it on a well known public source (there everyone can see that you published it)

In this publication, add a line: Originally published on dd/mm/yyyy by the owner of xxx@gmail.com

No need to encrypt anything.

Of course there is the chance that you don't want to publish your results yet. In that case you need to encrypt everything except the line with the email address. However, now it may be harder to get this published on a renowned site.


问:
More than 20 Records Inserted in a Span of 1 Sec
Well, this is not specific to any programming languages. I came across this situation in Android, iOS, PHP and .NET.

The problem is many times I come across a situation while building IoT apps, where I need to call a webservice (each in a separate thread) which does the insert into DB (probably more than 20 - 50 insert in a sec) to log the sensor data continuously.

So I face 2 problems here...

In the app end, it stops responding for creating so many threads.

In the server end, it also hangs due to so many inserts.

Sometimes, in Android and iOS programming I need to do the same in SQLite DB. In that case too it hangs in such cases.

The only option that I'm aware of is using Message Queue (which is specific to .NET I guess)

Are there any other way to solve these type of cases?

答:
Solving this problem is one of those situations where using a data abstraction layer (DAL) in your webservice might help you.

In your DAL on the server component, realising that there is a performance issue, you could replace the DAL code which writes directly to the database with one that implements a write cache.

That should allow the system to handle any spikes in inbound traffic, although if the problem is sustained writes or volume then you may need another optimisation - but so long as your webservice uses a DAL then you should be able to rewrite it with minimal fuss.


问:
I am not a good programmer (in logic), how should I fix it?
Ok, so here is my problem:

I work for a big company, some how landed a job (frankly because the interview was easy). It's not that I don't know my stuff, I am pretty good at understanding java, it's libraries etc.

But, when ever I try to solve some logic problem, I find it really hard to come up with a solution.

For example, conversion of decimal to roman, when I saw the solution, I find that it's a simple problem. But I was not able to implement it after 1-2hrs of trying out!

I feel I am dumb and not worth being a software engineer. Puzzle solving abilities should come natively to a great programer. But when I try to solve some puzzles, I am not able to find a solution and I just google it up!....and I hate that!

When given a problem (like implement xyz feature) at work, I am fairly pretty quick at it and am respect at my work place for that, but I am not at all proud about it. Because when I try to solve any mathematically or logic wise challenging problem, I fumble. I still feel I love what I am doing (as an engineer) but feel really sad that I am not able to solve some tough logic problems which I friends come up with.

I feel demoralized :(

TL;DR: I understand stuff from a practical viewpoint (implementing
  features in our product) but when trying to work on problem from say
  ProjectEuler, I SUCK badly! And I need to Sharpen my brain!

So, my questions are:

How should I go about fixing it? Should I start with solving (and forcing my self to) project euler problems? Even if it takes hours for me to solve some basic problems?

Or should I go back to basics and study some basic math?

I don't really find puzzle solving fun. But I want to make it fun for my self! And I think if I understand them in a better manner, I will like it!

PS: I was never educated in CS (my undergrad was electrial). But that's not an excuse to be a sucky developer.

Thanks!

答:
I feel I should add to this.

As the chosen answer has already stated, knowing your weakness is a huge advantage, and there are some basic tools for learning problem solving techniques.  What I think is lacking in the answer, though, is simply just to find ways to practice difficult problems - a lot.  Be stubborn about fully finishing every problem you try.  Reading code, lots of code, is good, as is reading books on the subject of problem solving, but writing code is almost more important.

In some ways, we share the same weakness (although, it is not as bad as you think).  To practice my problem solving skills, I am always working on some project Euler or HackerRank problem.  If it's an easy problem, I pick 7 programming languages and try to solve it in all of them.  For harder problems, I might pick 3 languages that are very different from each other, just to keep the time I spend on the problem reasonable.  For all of the problems, once I've come up with a solution, I search out the solutions others have come up with and make sure I understand them.  If you don't understand some solution, you can always post to StackOverflow or probably even here to Programmers Stack Exchange or something and I'm sure there's someone on the site who could answer your question (it's rare that there isn't).

Basically, though, make sure you are practicing, and not just reading, and practice a lot.  Just like sports, clear thinking takes time and effort.

Another thing you can do to help aid the way you think about problems is to write the test suite for the problems you solve first.  You cannot write a good test for a problem without first fully understanding it.  If you do this for different languages, this has the advantage of teaching you different testing techniques at the same time.


问:
OK to make a method generic just to pass in a System.Type?
Sometimes I have a function that takes a System.Type parameter, like:

```<code>public void Foo(Type type) {
    // do something with "type"
    ...
}
</code>```

This must be called like this:

```<code>Foo(typeof(MyType));
</code>```

I would like to rewrite it like this:

```<code>public void Foo<T>() {
    var type = typeof(T);
    // do something with "type"
    ...
}
</code>```

That way, my callers don't have to specify the "typeof" operator every time they call my method:

```<code>Foo<MyType>();
</code>```

Is this OK or is it an abuse of generic types?

答:
I wouldn't say it's an abuse. It's certainly something you can do with generics, and it sometimes makes your code cleaner. Here's the caveats:

While it's super easy to go from generic to Type it's very difficult to do the opposite. If your caller is likely to have a Type variable rather than calling your stuff with an explicit type... maybe reconsider.

It should be exceedingly rare that you work with Types directly, since reflection is often the only useful thing you can do with them - and you should be avoiding reflection use. Consider if you really need the Type or if you're doing something dirty to cause that requirement in the first place.


问:
Non-anemic model and SRP
I'm implementing a feature in legacy system right now.
Instead of putting all my logic in some dummy application services and having anemic models, I thought I will try to do some OOP this time.

I'm not using DDD, but trying to follow DDD-like-style a little bit.

So imagine a situation where you have:

```<code>public class CustomerAccount {
    private CustomerAccountId customerAccountId;
    Collection<AccountEntry> accountHistory; (or maybe some AccountHistory class)
}
</code>```

now, our Account has some domain logic.
It should be able to calculate total debit, credit and averageBalance within some time period.

So it would be like following

```<code>public Money calculateTotalDebit(Date start, Date end) // or maybe some TimeInterval, it doesn't matter

public Money calculateTotalCredit(Date start, Date end)

public Money calculateAverageBalance(Date start, Date end, FancyCalculationStrategy strategy)
</code>```

It also has some constraint that should be preserved while invoking other operations like addAccountEntry(AccountEntry entry)

So I can assume, that my Account is something like DDD's aggregate root.
Obviously, it's not real aggregate root, because I'm not applying DDD, but let's just say I see some similarity.

And now my Account class grows - there's quite a lot logic in each of those methods.
How is this related to Single Responsibility Principle? A class should have only one reason to change, but in this case, there are more. Or maybe not? Somehow I feel all this logic should belong to one place.

Yeah, I can create AccountHistory class, which encapsulates the behaviour, but this doesn't solve the problem - in that case, AccountHistory class will start to grow.

What I can do, is just to create some, let's say

```<code>AverageBalanceCalculator
</code>```

and delegate the behaviour.

But isn't it going towards anemic model again? This calculator will probably have no state and it will behave just like a service.

Of course it doesn't have to be visible to end-user - from the implementation point of view, it could be a package private class.

How is SRP related to aggregates root and other DDD's tactical patterns in general?

I'm little confused, would appreciate some answers.

答:
You're overthinking this.  If your class is:

```<code>public class Bill {
    private BillId billId;
    Collection<BillEntry> billHistory;
}
</code>```

Then your Average Balance method properly belongs in the Bill class.

```<code>public class Bill {
    private BillId billId;
    Collection<BillEntry> billHistory;

    public decimal GetAverageBalance()
    {
         return billHistory.Sum(x => x.Balance);
    }
}
</code>```

However, you should think carefully about how you are modeling this.  Normally, average balances are calculated on a Customer Account object, not a bill.

Title: Non-anemic model and SRP

Body:
You're overthinking this.  If your class is:

public class Bill {
    private BillId billId;
    Collection<BillEntry> billHistory;
}

Then your Average Balance method properly belongs in the Bill class.

public class Bill {
    private BillId billId;
    Collection<BillEntry> billHistory;

    public decimal GetAverageBalance()
    {
         return billHistory.Sum(x => x.Balance);
    }
}

However, you should think carefully about how you are modeling this.  Normally, average balances are calculated on a Customer Account object, not a bill.


问:
Where should I store test data?
I have smaller unit tests that use small snippets from real data sets. I would also like to test my program against full data sets for a multitude of reasons. The only problem is that a single real dataset is about ~5GB. I haven't found any hard numbers for what Git repositories can store but that seems like too much.

(According to this Programmers post I should keep all of my data needed to test the project in the repository.)

The solution that my team has adopted is that the project has a file that contains a path to a network attached file system that holds our test data. The file is Git ignored.

I feel like this is an imperfect solution for two reasons. When the NAS isn't working, is slow, or is down than we can't run a full test. The second reason is that when someone first clones a repository the unit tests fail so they have to figure out how to mount things with a certain name and the syntax used to build the testing path file.

So my question is two fold. How much data is too much data to store in revision control?

What is a better way to handle large amounts of test data?

答:
...when someone first clones a repository the unit tests fail so they
  have to figure out how to mount things with a certain name and the
  syntax used to build the testing path file.

First, just to have a consistent terminology: This kind of test (large external dependencies, real data) is usually not considered a unit test, but rather an integration or system test.

On a practical note: I find it a good practice to keep unit and integration tests separate, because they have different strenghts and weaknesses.

separate the two kinds of tests in the code (naming convention, separate project, ...)

provide a way to run only one of the two suites of tests

run only the unit tests during normal builds

run the integration tests on demand, and on a CI (continuous integration) server

That way, local builds are fast and reliable (little/no external dependencies), and integration tests are handled by the beefy CI server.
This avoids the problem you describe.

As to how to keep the data:

One good option is some kind of artifact management like ptyx' answer describes. Another would be to put the test data into a separate repository. The data is not released together with the main build anyway, and having a separate repo avoids forcing everyone to fetch the test data along with the source code. In other words, use a second repo as your artifacdt management :-).

ContentLicense: CC BY-SA 4.0

Title: Where should I store test data?


问:
can a closed source commercial software make system(3) calls to GPL applications (not libraries)?
The closed source commercial software (CSCS), will just make system(3) calls to GPL applications.

The user machine will run CSCS and it will call these GPL applications, in realtime, in the very same way a user could use the command line and call the very same applications. Even a log of such actions could be provided, and user could replicate these actions manually.

In Java it would be like: Runtime.getRuntime().exec("echo Hello");

In C it would be like: system("echo Hello");

The point is, the CSCS is calling a GPL application to just generate realtime output, and in a predetermined way and hard coded on it, so CSCS depends on GPL app to work.

The GPL application is NOT a library. Is a regular command line application.

And, I am NOT going to distribute any GPL application (neither its sources) packaged together with CSCS. It will just depend that the OS have such GPL apps already installed. Also, CSCS can run with at least the version of the GPL application that was used in the development time (or newer), so it will NOT depend on a specific GPL app version to run.

1) Can the CSCS remain closed source on this sole specific situation?

2) Or should CSCS only use statically generated output from GPL applications, being prevented to use them in realtime, if it wants to remain closed source?

3) Alternatively could be created a LGPL software composed by scripts like ls -l $1 whose parameters would be dynamic data provided by any application including this CSCS. In this case, all the logic of these scripts would be exposed and reusable by anyone, therefore not proprietary. So, such "protocols" would all be LGPL. Can that be done? Or this would simply fall under something like indirect use of GPL sofware, and so GPL would infect every application using it (including this very LGPL software, forcing it to become GPL)?

I would appreciate also excerpts confirming the answer, thanks!

PS.: I have read this Can I use GPL software in a commercial application, and it doesnt seem to answer my specific question.

And, I need to know this before I can consider any kind of realtime GPL application usage on my software.

Linking: https://softwareengineering.stackexchange.com/a/161938/112610

I was unable to avoid linking this: https://meta.stackexchange.com/a/91116/222324

Another Link: https://softwareengineering.stackexchange.com/a/211357/112610

Obs.: (2 days after, considering all commented tips and answers) These may contain the answer:

A) I think this very question could actually be "What is a GPL derived work?" considering the "Networked Systems" section.

B) See "Mere Aggregation" in the GPL FAQ "pipes, sockets and command-line arguments are communication mechanisms".

PS.2: just as a final disclaimer, we all here seem to not be lawyers, and even if you do it all correct in this line, and even if you are sure of your license interpretations, something you do not expect may happen, https://softwareengineering.stackexchange.com/a/158925/112610

答:
And, I am NOT going to distribute any GPL application (neither its sources) packaged together with CSCS.

Copyright controls who is allowed to distribute something, not who is allowed to use it.  If you don't distribute the GPL application, you can't infringe copyright, even if you depend strongly on it.

Your user could infringe the conditions on which they got the application you use, but GPL does not include such clauses.


问:
Is there a common set of best practices for passing anonymous functions as arguments?
This is a generic question about using anonymous functions as arguments to other functions. I give an example in Python, but the question is not about Python (and I'm particularly interested in whether answers might be different for functional languages than for other paradigms).

In Python it is common to pass an anonymous function as an argument to another function, for example:

```<code>sorted(my_data_structure, key=lambda x: x[0].foo)
</code>```

where lambda x: x[0].foo is an anonymous function to return the foo attribute of the 0th element of each thing in my_data_structure (under the assumption that whatever lives in my_data_structure will have a 0th item and that 0th item will have a foo attribute).

To my mind, in all but the simplest cases, this presents a problem for encapsulation and extensibility: what if my_data_structure changes? What if the attribute to sort by becomes bar in a later code refactoring? Now you've got to descend into the actual lambda to deal with it.

Alternatively, this could have been written as:

```<code>def my_helper(some_data_thing):
    """My intentions are ____ !
    """
    return some_data_thing[0].foo

#Elsewhere in the code:
sorted(my_data_structure, key=my_helper)
</code>```

While this adds 4 lines of code, it is more readable. You don't have to parse whatever the lambda is trying to do at the moment you read about the call to sorted. It gives the opportunity for type annotation, documentation, or even unit-testing to occur for the helper function.

If something changes, but you still want the local code around the use of sorted to remain the same, this nicely encapsulates that for you away into the helper function. And if more than one place needed to sort, or group, or whatever, by the same key, you get code reuse better than reproducing the lambda is many locations.

However, others might also say that you are bending over backwards to give a name, my_helper, to a little function that is actually more clear to just see it in code directly.

I can agree with this to an extent, especially when the lambda involved is very small, but what if it needs to be a multi-line lambda that runs into a lot of indentation issues, or involves a somewhat obfuscated list comprehension or some other device?

My question is: what approaches exist for determining where to draw the line between a useful in-line anonymous function that is "self-contained" enough that it is more effective to write it directly versus an in-line function that is too complex and should be wrapped in a helper function. Are there other considerations I'm not taking into account?

For example: this post on this issue in JavaScript states and affirms many of the concerns I've listed. Is this codified for programming in general? Is it language or paradigm-specific? And what about the other side of the debate?

答:
You draw the line based on length and repetition.  A lambda is okay if it's short and not repeated.  Once you get into multiple lines, or are repeating it multiple times, you should really give it a name.  If your data structure changes, it's no big deal to change one or two short lambdas, especially in a strong statically typed language.  For some reason, though, lambdas give people a blind spot to repetition.

JavaScript is really the only language I've seen where multi-line anonymous functions are commonly accepted.  I'm not sure what it is about the language that makes it that way.  It may be more a cultural thing.  That doesn't make it a best practice, however, just a common one.  Also, the same rules apply about repetition.  More so, since repetition of longer functions is worse.


问:
Best approach to implement an update operation of a container object?
I have an Invoice object wich may contain several FacturedServices objects stord as a list.

In may interface, the user can edit an Invoice object, delete add or edit its FacturedServices list.

Whe the user hit the save button, the updates made to  Invoice object should be passed to the database as well.

The problem is the FacturedServices list will contain heterogenous data, because some of its elements are new, others changed and some of them have been deleted from the list.

What is the best way to implement hte update of the Invoice object in the database ?

I was thinking to add a dirty property on every FacturedService object, whenever it is changed, or set the property to "new" when its newely created and then do some if else in my controller :\

If you think my question should be rephrased, please do it

EDIT :
Say I have an object Invoice I
, It has 3 FacturedServices FS1, FS2, FS3

In the interface, the user edited FS1, deleted FS2, and added FS4 to the list

now the list contains edited FS1, unchanged FS3 and newly created FS4.

in my databse, I have an InvoiceTable and a FactureServicesTable whith a referencial inetgrety to the invoice id.

my problem is in my controller there must be a way to know which FS is new which one is updated and which one was deleted, so I can execute the correct SQL commands depending on the situation.

I know this is not something new, in every desktop application at some point there should be something similar to my problem. so what is the best way to do this.

答:
I just will save the opearations made by the user and the concerned objects in a Map <String, List<FacturedServices>>. If a user delete a FacturedServices, it will be added to the map with a "DELETE" key. Then I will iterate over the map and execute delete, update or create commands according to keys. A more professional solution would be to implement a command pattern, but this is just fine for the moment, if you think of something better let me know, I will be pleased to discuss it.

Thank you for your time


答:
It's possible to hash the data you wish to timestamp and turn it into a Bitcoin address.  This is known as trusted timestamping.  By making a small payment (a satoshi, or 0.00000001 BTC) to it, the payment is stored on the blockchain along with the address you paid to.

Since only the hash is stored on the Bitcoin blockchain, no one can tell what data you stored, but given the pre-hashed data you can prove the data was created prior to the block that contains the payment made to that address.


问:
Should I put logging in common shared libraries?
Should you add logging to common libraries that are used in many applications? For example, if I have a parser that's used in multiple apps, should I add logging inside the parser? My concern is that it couples all users to the logging framework.

I'm particularly interested in solutions for shared libraries that are used outside of the implementer's organization. For instance, would Microsoft add logging into any of the base class libraries? Why or why not? What options are there for troubleshooting if you leave out logging?

答:
If coupling users to the logging framework is an issue, you may use:

Either Dependency Injection to make the consumers of the shared library provide the library with the logging feature.

Of course, this means that either there is a common logger interface which is standardized enough, such as PSR-3 for PHP, or you are able to provide an interface generic enough to make it possible to create adapters for different logging frameworks.

The pros of this approach is that you don't need to handle different logging frameworks yourself: you may provide an implementation for your logging interface for your preferred logging framework, and let consumers create their own adapters for other logging frameworks.

The cons is that designing a good interface which will be easy to use with any logging framework may not be an easy task. Using a standard (PSR-3 being an example) as a foundation can be helpful.

Or use application configuration to determine which one of the logging frameworks should be used.

This requires to have a standard for configuration files: some languages/frameworks do have one, such as .NET Framework (app.config/web.config files). Unfortunately, others do not (such as node.js).

The pros is that consumers don't have to do anything special to make your library work for them. If they don't need logging, they don't configure anything. If they need logging, they select a logging framework among the supported ones and configure it in the same standard way they would do for their own application.

The cons is that while you may provide support for mainstream logging frameworks, one day you'll have to accommodate your library for a new framework. Also, providing support for multiple frameworks may make your library grow in size and increase the number of dependencies, unless you use plugins which are usually difficult to implement.


问:
What is the "default" software license?
If I release some code and binaries, but I don't include any license at all with it, what are the legal terms that apply by default (in the US, where I am). I know that I automatically have copyright without doing anything, but what restrictions are there on it?

If I upload my code to github and announce it as a free download / contribute at will, then are people allowed to modify and close source my work? I haven't said that they cannot, as a GPL would, but I don't feel that it would by default be acceptable to steal my work either.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?

答:
One thing which may be significant is that you mention Github.

If you're using a free Github account that's an implicit statement that it's OpenSource.  Even if you don't include a license the fact that Github free accounts are only permitted to host OpenSource projects would almost certainly allow people to claim a reasonable expectation that that's what it was.

Section F, paragraph 1 of the GitHub Terms of Service says:

We claim no intellectual property rights over the material you provide
  to the Service. Your profile and materials uploaded remain yours.
  However, by setting your pages to be viewed publicly, you agree to
  allow others to view your Content. By setting your repositories to be
  viewed publicly, you agree to allow others to view and fork your
  repositories.

Title: What is the "default" software license?


问:
Domain Driven Design and Data Conflicts
I realise it is probably overkill for what is a occasionally connected client app, but the construction of aggregates roots is bugging when thinking about it from a client perspective.

For the purposes of providing domain visualisation, let's just say that whole system is concerned with arranging and editing meetings with customers.

Now, the domain model is set up fine and is able to define itself properly OUTSIDE of the need to interface with another system. However, uploading client data to an external system can result in in Data conflicts (update, delete, etc) which in turn will raise UserAlerts.  These will require action from the client user in order to resolve. (eg Viewing the two records before merging and saving into one).

So firstly, it strikes me that the main domain model's overall purpose is quite distinct from the need for a user to resolve a data conflict.  So in this sense, I would expect UserAlerts to be separate from the meeting aggregate.

However, resolving an alert will surely need to be conducted within a transaction, since the alert itself should not exist without the meeting object.  So in this sense, it seems that it would make sense for the alert to be contained within the aggregate.

So, I am confused with regards to this.  Has anyone out there modeled a similar situation? (I have a temporary solution in place already, but I would just like to know what people think is the correct way of doing things).

答:
I suppose that if resolving data conflicts is a part of technical considerations which you cannot remove, then whatever is required to resolve such conflicts does belong to the domain.

You could have two interface layers for that, though.

The simpler layer, oblivious of conflict-resolution needs, can be used wherever conflicts cannot arise (e.g. querying and visualization), and be published more widely.

Its more complicated superset, the one which allows to see and resolve conflicts, can be used only where conflicts can happen (e.g. updating or replication logic), and be constrained to that narrower area. If you rework the conflict-handling logic, the clients that don't work with conflicts will not notice it and will not need an update.

Title: Domain Driven Design and Data Conflicts


问:
Storing 5000 elements on client side in a web application
I just had a phone interview for ASP.Net developer, after initial introductory stuff the interviewer ask me first technical question:

"How would you store 5000 elements on client side for each user in a web application".

My answer started with,

What is the average size of each element ? Do we really have to store this much data on client side ? Can't we keep that in the database and link this to user session/client ID somehow.

His reply was "No, You tell me how would you store it on the client side, considering that each element is a record with around 8 fields including int/string, a normal table row".

I said, "May be keep them in a session, but since sessions are maintained on server side for each user, It could become expensive, or the other option is to store that much data in cookie", I also said that I am not sure if that much data could be stored in cookie. I mentioned HTML5 Storage options is there, but I haven't worked with it. Since it is based on SQLite, it could store that much data theoretically.

That's where the interviewer somewhat sarcastically said, so you have 3 years of experience in web development, and terminated the interview.

I am wondering, what I did wrong? or is there something really basic that I am missing with respect to storing data on client side.

答:
The 'correct' answer - at least, the one they were looking for - was indeed HTML5 LocalStorage (an excellent link by Steven Burnap). And the interviewer was probably being...well, I believe the technical phrase is "a bit of a knob".

This is basically arrived at by process of elimination, in that a cookie cannot be anywhere near big enough, sessions are indeed server-side and not a client-side storage mechanic at all, etc. The interviewer presumably thought this was common knowledge and you should know it, which is funny in that you only need HTML5 LocalStorage capabilities typically in data-heavy UI work which is the exception rather than the rule. A person could program for many years and not have need for the feature, while others might have a need for it on their first project.

However, I would generally say in cases like this it's less a question of your answer and rather a question of how you answered it and the process you used to get there. From your description you did OK, but I wasn't there and so their impression might be very different.

Most sensible interviewers won't declare one small facet of technology a litmus test where every person must answer it great...however, I've had a lot of interviews with people who aren't sensible interviewers. Knowing such trivia can be a boon when you run into such individuals.

Finally, I would note that by declaring the interview over in rather a not-very-nice way, it is highly likely that the person was already annoyed and had decided about you already (your answer to this specific question might not have mattered in the slightest). They were just waiting for a moment for you to trip up so they could point at it and not expose the fact that they'd decided in the first 30-seconds or so if you were a viable candidate or not.

I'd perhaps practice how to answer questions you don't immediately know the "right" answer to, as the ability to be wrong gracefully and seem knowledgable and intelligent anyway is a darn handy skill - and we all could benefit from the extra practice. Brush up on some "what's new in [latest version of important technology]" articles and then get back out there!


答:
I agree with the comments that he was likely looking for HTML5 local storage, and may have expected you to have experience with it.

Frankly, unless it was an integral requirement of the job and you stated you had experience with it, his expectation and reaction were unreasonable, in my opinion, for anyone with any amount of experience.

Why?

Because, three years ago, HTML5 as a spec was still in its infancy. In other words, for you, specifically, your career is about as long as the history of the spec itself. It's not uncommon to see jobs looking for people with more experience with a product than the product has been around. It's rare to see the same happen for an entire specification. For that, I applaud you for finding such a gem.

More seriously, though, it sounds like the issue lies more with your interviewer asking you an overly vague question, and judging you too harshly on it. It's not uncommon for interviewers to ask vague questions, especially in the development arena. Usually, this is done to try to gauge how you think, and where your first instinct leads you. For that, you did well by questioning the need to store that kind of data locally. These questions are not, in and of themselves, bad, but what the interviewer does with them can lead to a bad outcome for you (arguably, such interview termination means you probably don't want to work for that company, anyway).

Now, it's possible that the company's business needs required they use local storage for one reason or another. If that's the case, it should have been spelled out in the job description, and you should have been ruled out as a potentially viable candidate when your resume reflected no such experience if they felt they couldn't or shouldn't train or otherwise provide the new employee with the time/means to come up to speed on the technology.

As for local storage, itself -- as I mentioned previously, HTML5 as a spec has only been around for about three years, and that's being generous and counting the "last call" drafts. Then, you have the issue of browser support, which may or may not have a long history (for example, while name-value pairs have been widely supported even prior to HTML5 solidification, IndexedDB and Web SQL DB are still sketchy).

Finally, the usage for HTML5 local storage is less common still. In my years as a web developer, I've come across an app that I know utilized it all of once (there may be some that use it invisibly, but that's harder to quantify), and maybe half a dozen projects that may be able to make use of it (but didn't really need them at that time, or the cost of using that approach vs another wasn't justified).

In a more general sense, failed interviews happen. Software development is far too big a field to be able to know all the little details about every single thing (in this case, the storage limits of HTML5 local storage), and being honest about not knowing a given thing is, in my opinion, still the best route (I personally have more respect for someone who acknowledges their gaps in knowledge and seeks to fill them, than for someone who tries to cover up the fact that they don't know something). With that in mind, I'd say you handled the question well, given the information you've given here. If there was something you did wrong, it may have been in the details of how you responded, which we can't help you with, here, because we weren't at the interview to assess the non-lingual aspects of your responses.

Title: Storing 5000 elements on client side in a web application

Body:
I just had a phone interview for ASP.Net developer, after initial introductory stuff the interviewer ask me first technical question:

"How would you store 5000 elements on client side for each user in a web application".

My answer started with,

What is the average size of each element ? Do we really have to store this much data on client side ? Can't we keep that in the database and link this to user session/client ID somehow.

His reply was "No, You tell me how would you store it on the client side, considering that each element is a record with around 8 fields including int/string, a normal table row".

I said, "May be keep them in a session, but since sessions are maintained on server side for each user, It could become expensive, or the other option is to store that much data in cookie", I also said that I am not sure if that much data could be stored in cookie. I mentioned HTML5 Storage options is there, but I haven't worked with it. Since it is based on SQLite, it could store that much data theoretically.

That's where the interviewer somewhat sarcastically said, so you have 3 years of experience in web development, and terminated the interview.

I am wondering, what I did wrong? or is there something really basic that I am missing with respect to storing data on client side.


问:
Is there a subset of programs that avoid the halting problem
I was just reading another explanation of the halting problem, and it got me thinking all the problems I've seen that are given as examples involve infinite sequences. But I never use infinite sequences in my programs - they take too long. All the real world applications have lower and upper bounds. Even reals aren't truly reals - they are approximations stored as 32/64 bits etc.

So the question is, is there a subset of programs that can be determined if they halt? Is it good enough for most programs. Can I build a set of language constructs that I can determine the 'haltability' of a program. I'm sure this has been studied somewhere before so any pointers would be appreciated. The language wouldn't be turing complete, but is there such a thing as nearly turing complete which is good enough?

Naturally enough such a construct would have to exclude recursion and unbounded while loops, but I can write a program without those easily enough.

Reading from standard input as an example would have to be bounded, but that's easy enough - I'll limit my input to 10,000,000 characters etc, depending on the problem domain.

tia

[Update]

After reading the comments and answers perhaps I should restate my question.

For a given program in which all inputs are bounded can you determine if the program halts. If so what are the constraints of the language and what are the limits of the input set. The maximal set of these constructs would determine a language which can be deduced to halt or not. Is there some study that's been done on this?

[Update 2]

here's the answer, it's yes, way back in 1967
from http://www.isp.uni-luebeck.de/kps07/files/papers/kirner.pdf

That the halting problem can be at least theoretically solved for ﬁnite-state
systems has been already argued by Minsky in 1967 [4]:
“...any ﬁnite-state machine, if left completely to itself, will fall eventually into a
perfectly periodic repetitive pattern. The duration of this repeating pattern cannot
exceed the number of internal states of the machine...”

(and so if you stick to finite turing machines then you can build an oracle)

答:
There is, and in fact there are programs in real life that solve the halting problem for other problems all the time.  They are part of the operating system you are running your computer on.  Undecidability is a weird claim that only says that there isn't such a program that works for ALL other programs.

One person correctly stated that the halting proof seems to be the only program for which it cannot be solved, as it infinitely traces itself like a mirror.  This same person also stated that if there was a halting machine, it would be magic because it would tell us hard math problems by telling us ahead of time if it's solver algorithm would halt.

The assumption in both of these cases is that the halting machine doesn't trace because there is no proof that it traces.  However, in reality it actually does trace/ run the program it is run on with the input given.

The logical proof at least is simple.  If it didn't need to trace at least the first step, it wouldn't need the input along with the program it's run on.  In order to make any use of the information, it has to at least trace the first step before trying to analyze where that path is going.

The hard math problems mentioned in the top answer are ones where you cannot fast forward to figure out the answer, which means the halting problem would have to continue tracing until some pattern was recognizable.

So the only practical argument to get from the halting problem is that a halting machine can't determine the outcome of an optimized problem solver faster than the problem solver can finish.

Giving a formal proof for this reasoning is harder, and although I believe I could, attempting to explain it to anyone an academia will result in them throwing an ape like temper-tantrum and swinging from the chandelier.  It's best just not to argue with those people.


答:
Is it misleading to label classes or methods as a particular design pattern (Strategy, Mediator, etc.) if they only loosely fit that definition?

No, it is not misleading; rather it should not be.

Too Loose Obstructs Understanding. If we say a global read only variable is a singleton, that's not "loose" that's just wrong. Besides, strictly speaking a "singleton" is how the object is constructed; that object could very well be one of the structural patterns.

Modern language constructs can let us adhere to the intent of a given design pattern but deviate from the classical class model as seen in the GoF book. For example in the Command Pattern, concrete commands are subclasses (or implement an interface). However one could use a delegate for the "command method" without subclassing. The command pattern goal is met: decoupling the requester from the execution of the request.

Intent matters. There is similarity between some patterns but the slight, seemingly pointless, differentiation expresses intent of the pattern. For example look at the striking similarity between the Composite and Decorator patterns.

Specificity. For example it is not enough to say "factory". "Factory Method", "Factory class", and "Abstract Factory" each express increasingly complex solutions to the general idea of separating object construction from its use. Then consider the Builder pattern which could be described as a flexible Abstract Factory.

Title: Is it misleading to label code as a particular design pattern if it only loosely fits the definition?

Body:
Background:

I have a rough, but working understanding of ~15 design patterns. It's been my experience using design patterns in my own projects that the resulting implementations usually end up as some variant of a pattern and don't always fit the canonical textbook examples.

Case:

I find it useful to leave tag-like comments that hint at an underlying archetype, e.g., in the following Javadoc class description, the "[Singleton]" label is used merely to describe that there's only one of these objects used at any given time. This class may or may not be set up to "restrict the instantiation of a class to one object" --Wikipedia.

```<code>/**
 * [Singleton]
 * The manager of all jewels, which are stored here in collections.
 */
public class JewelManager implements IDestroyable
{
</code>```

Context:

I'm working on a team with several other developers, but I need to assume there may be other devs working on the project with whom I will never have the opportunity to speak.

Question:

Is it misleading to label classes or methods as a particular design pattern (Strategy, Mediator, etc.) if they only loosely fit that definition?


问:
How to model and store an entity which has "one or more" values
I'll use C# to design the model to be persisted

Let's suppose I have the following entity:

```<code>public class Episode {
     public int Id { get; set; }
     public string Title { get; set; }
     public string Image { get; set; }
}
</code>```

This a very simple entity, which is easy to map to a relational model.

But, what about if I want my Episode entity to have one or more images?

How would I represent this?

I can, for example create this entity model:

```<code>public class Episode {
    public int Id { get; set; }
    public string Title { get; set; }
    public ICollection<string> Images { get; set; }
}
</code>```

But this, does not assure I have at least one image in my collection.

Furthermore, how would I design the relational model for this entity? How can I represent an entity that has a "1 to many" relationship with a string?

Do I need to create an additional table just for storing these "strings"?

I would really appreciate any advice you may want to share, and the best approach to this problem

答:
First you have to decide if it is sufficient to have runtime safety about the number of images or if you want to have compiletime safety.

Runtime safety

Achieving runtime safety is quite easy. All you have to do is remove the default setter for Images and implement a setter that performs a check before saving the given ICollection<string> argument regarding if the collection has at least one element. Also make sure, that there is no way to change Images other than using this safe setter.

The drawback is of course, that one can try to call the setter with an emtpy list and your IDE won't show you that it will fail at runtime.

Compiletime safety

To get compiletime safety you need to spend more effort. As you recognized, a collection makes it able to store no items in it. That belongs to its contract and that is totally fine. However in your case, you don't want that. Therefore, the a collection is not the correct type and you need to create you own type. My best idea is to create a class that implements the list specific features and delegates it to an internally saved list. However, the methods that could set the internal list empty, have to be intercepted to make sure the list is never empty. In the constructor you then have to do something messy. It has 2 parameters: T Head and ICollection<T> Rest (both must be not null). The Head and all items of the Rest are then put into the interal list. When the first argument T is not null then the interal list is not empty for sure and as you intercept all the methods that change the list, you can make sure it will never become an empty list.

It is not very elegant in my opinion because you can't create this type just from a list. But in exchange you get compiletime safety, so everyone trying to instanciate this datatype empty, will have the IDE complaining because it is not possible.

About your additional question for storing it in the database: Yes, I think the only way is to have an additional table for the image-strings because it is "1 to many". There is no way around this unless you give up the normalisation.


答:
There are a few options:

Just use a regular ICollection, document the fact that it must be non-empty, and enforce this in the setter. In the database, you would have a episode_images table. This doesn't provide the compile-time safety you're seeking, but in my opinion it's the only reasonable option.

You could store a FirstImage field and a OtherImages field. In the database, you could have a first_image column in episodes, and a other_episode_images table. I wouldn't suggest this approach as it would be awkward to work with that API.

As @valenterry said, you could introduce a new non-empty collection type, which could store FirstElement and OtherElements fields. I wouldn't suggest this as callers wouldn't like being forced to work with a non-standard collection type.

Do I need to create an additional table just for storing these "strings"?

If you really don't want an additional table, you could store serialized collections in a text column, like ["image1", "image2", "image3"]. But a separate table is more idiomatic, and it works better if you need to do some analysis from a SQL console, such as finding the episode with the most images.

Title: How to model and store an entity which has "one or more" values

Body:
I'll use C# to design the model to be persisted

Let's suppose I have the following entity:

```<code>public class Episode {
     public int Id { get; set; }
     public string Title { get; set; }
     public string Image { get; set; }
}
</code>```

This a very simple entity, which is easy to map to a relational model.

But, what about if I want my Episode entity to have one or more images?

How would I represent this?

I can, for example create this entity model:

```<code>public class Episode {
    public int Id { get; set; }
    public string Title { get; set; }
    public ICollection<string> Images { get; set; }
}
</code>```

But this, does not assure I have at least one image in my collection.

Furthermore, how would I design the relational model for this entity? How can I represent an entity that has a "1 to many" relationship with a string?

Do I need to create an additional table just for storing these "strings"?

I would really appreciate any advice you may want to share, and the best approach to this problem


问:
Explicitness, verbosity and their counterpart - when to prefer which?
I'am the only one in my team who advocates for adding a little implicitness in favor of codebase reduction and decreasing repetition. Yet I don't want to be a biased 'Bad apple' playing against working design which was created prior my arrival at this job. Attempts to change the approach can be taken too personal by some teammates and just saying 'mine is better than yours' promisses the opposite result.

Trials to find cons of the proposed and pros of existing solution are the best way to fight against biases - so called 'devil's advocate' game. Unfortunately, it's quite diffcult sometimes.

The broad question sounds like this:

Are there any clear (measurable?) guidelines (besides "it depends") for setting the degree of explicitness/inderection.

The narrow question is quite local, nonetheless I dare to ask for the list of pros and cons of both approaches.

Our server application has several layers: Service, Business Logic, DAL.

For any data modification (create+update, no deletes) we also save authenticated user stamp thus havig the history who did what.

Current implementation gets user name from framework MVC/WCF and passes it across the layers as an additional argument to the methods just to pass the value to the next layer until it reaches the session object which manages the transaction. (DAL)

I offer to use AmbientContext approach: Userstamp is set once at the very beginning of the request processing pipeline and then implicitly flows with execution workflow (respecting async) and is accessible by any layer if required. Very similar to Thread.CurrentPrincipal.

答:
Are there any clear (measurable?) guidelines (besides "it depends") for setting the degree of explicitness/inderection.

Not many.

The first is the Law of Demeter, which focuses on how many "steps" it takes to get to what you want, which directly relates to your question about indirection.

Another is Tell, don't Ask. If you have some implicit state being carried throughout the program, objects necessarily need to ask about the state rather than being told about it.

Otherwise, it depends...

It is generally accepted that explicitness is better than implicitness. And your example question brings up other soft metrics: code coverage, bug count/severity, and team velocity.

If by making things implicit, you make it difficult/impossible to unit test your code, that is a fairly clear cut downside.

If by making things implicit, you cause there to be more bugs or more severe bugs (possibly due to worse/fewer unit tests? concurrency/reentrancy issues with the implicit state?) then that's a fairly clear cut downside.

If by making things implicit, you make the team produce code slower (harder to write unit tests? Harder to read? More time spent fixing bugs?) then that's a fairly clear cut downside.

And of course the opposite can be true - if implicitness allows you to make more code, with fewer bugs, then the positives are there. Like all other program design, it's a matter of trade-offs.


答:
You are asking two very different questions. The former one is not a generalization of the latter, because answering the first won't answer the second.

There are many other things that might influence the second question, like how you would tackle transactions with multiple users and such.

As for the first question, everybody agrees that a shorter solution to the same problem is preferable, provided it can also be understood. There is no absolute guideline for that, since understanding is subjective. Use code reviews to find a sweet spot that works for your particular team.

Title: Explicitness, verbosity and their counterpart - when to prefer which?

Body:
I'am the only one in my team who advocates for adding a little implicitness in favor of codebase reduction and decreasing repetition. Yet I don't want to be a biased 'Bad apple' playing against working design which was created prior my arrival at this job. Attempts to change the approach can be taken too personal by some teammates and just saying 'mine is better than yours' promisses the opposite result.

Trials to find cons of the proposed and pros of existing solution are the best way to fight against biases - so called 'devil's advocate' game. Unfortunately, it's quite diffcult sometimes.

The broad question sounds like this:

Are there any clear (measurable?) guidelines (besides "it depends") for setting the degree of explicitness/inderection.

The narrow question is quite local, nonetheless I dare to ask for the list of pros and cons of both approaches.

Our server application has several layers: Service, Business Logic, DAL.

For any data modification (create+update, no deletes) we also save authenticated user stamp thus havig the history who did what.

Current implementation gets user name from framework MVC/WCF and passes it across the layers as an additional argument to the methods just to pass the value to the next layer until it reaches the session object which manages the transaction. (DAL)

I offer to use AmbientContext approach: Userstamp is set once at the very beginning of the request processing pipeline and then implicitly flows with execution workflow (respecting async) and is accessible by any layer if required. Very similar to Thread.CurrentPrincipal.


答:
In the code:

Validate in the setter the collection has at least one item, and raise and exception if it doesn't.

In the database:

Create an episode_image table. That table would have a foreign key with the image table.

Unfortunately, there's no way to enforce that for every row in the parent table, there's at least one corresponding row in the child table. Only the other way around is possible. Imagine this: if foreign keys worked both ways, it'd be impossible to insert a row in A because corresponding row in B doesn't exist, but you couldn't insert the needed row in B either, because no corresponding row exists in A. That kind of constraints are possible in a conceptual model but not in a physical database.


问:
Returning the object/$this
A very general question. I was thinking about method chaining, which seems useful, and began wondering if there is a reason to not return the object in a class member, as a matter of course.

For instance:

```<code>function doStuffAndReturnThis() {
    /* Does Stuff */
    $this->variable = $stuff;
    return $this;
}
</code>```

I suppose it is like one of those arguments against always returning true/false;

Is there a consensus? Also, my main language is PHP, but thisn't a PHP specific question.

答:
Method chaining implies that multiple method calls are related, with each call building on the previous one. An example is a "fluent" style of programmatically querying the database.

```<code>$posts = Post::where(array('name' => 'Test'))
    .order_by(array('date' => 'desc'))
    .limit(10);
</code>```

(Forgive my lackluster PHP, it's been quite a while since I wrote any)

The Post class's where method returns a QueryBuilder object which has an order_by method and a limit method, both of which return the QueryBuilder object.

You'll see this fluent, natural language like syntax when an object needs a bunch of configuration that is conceptually easier to manage in natural language, such as ad hoc SQL queries.

Why not always return the object to promote method chaining? Because people could be making assumptions about you class's functionality that aren't true. If a method call doesn't require subsequent method calls to achieve the end goal then returning the object could make programmers think your class need additional calls when it doesn't.

Title: Returning the object/$this

Body:
Method chaining implies that multiple method calls are related, with each call building on the previous one. An example is a "fluent" style of programmatically querying the database.

$posts = Post::where(array('name' => 'Test'))
    .order_by(array('date' => 'desc'))
    .limit(10);

(Forgive my lackluster PHP, it's been quite a while since I wrote any)

The Post class's where method returns a QueryBuilder object which has an order_by method and a limit method, both of which return the QueryBuilder object.

You'll see this fluent, natural language like syntax when an object needs a bunch of configuration that is conceptually easier to manage in natural language, such as ad hoc SQL queries.

Why not always return the object to promote method chaining? Because people could be making assumptions about you class's functionality that aren't true. If a method call doesn't require subsequent method calls to achieve the end goal then returning the object could make programmers think your class need additional calls when it doesn't.


问:
Client vs Creator in Factory Method and Abstract Factory patterns
This page descibes one important difference between Factory Method and Abstract Factory:

http://architects.dzone.com/articles/factory-method-vs-abstract

The difference, according to this page, is that in Factory Method pattern the Creator (i.e. the entity creating new objects) and the Client (i.e. the entity using the Creator) are the same class. More precisely, this pattern only defines a method, so the rest of the class is the Client. In Abstract Factory however, the Creator and the Client are separate classes. The Creator's only purpose is to create objects so only a separate class can be the Client.

Is this distinction correct? If so, why can't the Creator method in the Factory Method be put in a separate class? Would it create any problems? Similarly, why can't the Creator class in the Abstract Factory be the same class as the Client? Would this create any problems?

Update:

Just as a side note: it's SHOCKING to me too see that when I ask about such well known and (what should be) well defined design patterns I get actually contradictory answers. And it's not just this thread - the more and more I ask people (or search online resources) about the basic design patterns the more I start to think that people don't actually TRULY understand them even though they're using them on a daily basis and they believe they understand them.

答:
Remarks about the question text

I threaten with good intentions that I will someday edit the question text to remove the disparaging remarks. Such remarks are not tolerated on Programmers.SE. If you have time, please edit the question text to remove it, so that I don't have to. Thanks.

Stated objective

I will try to greatly simplify the step-by-step transformation of the "factory-esque". In doing so, I promise to eschew the verbiage that has long plagued the GoF patterns (and any wannabes who try to be experts on patterns).

Step zero, the constructor method

The constructor method creates an object, initializes it, and returns the object to its caller.

In most languages, the caller must specify the leaf-type (also known as the "most-derived type").

This specificity requirement is a big constraint in view of polymorphism - the caller can't act polymorphically (i.e. "can't pretend to not know the class") if it needs to call a constructor, period.

Step one, ordinary factory method

An ordinary factory method wraps the constructor method.

It takes the arguments, constructs the object just as before (and lets the real constructor handle the actual initialization, as before), and returns it.

There are several differences.

Firstly, it removes the leaf-type specificity constraint from the caller's code. The caller's code now doesn't have to know the class name of the thing it's going to create.

Secondly, an ordinary factory method is an ordinary method. It can be:

A static method or instance method;

A member of the same class or of a different class;

Or even an interface method. (This will be discussed below, in Step three.)

Thirdly, and which is orthogonal to the other differences, is that: if the object to-be-constructed-and-returned belongs to some inheritance hierarchy, the ordinary factory method doesn't have to declare its return type (the type of object it promises to construct-and-return) to be the leaf-type. It can instead declare itself to return a base type, or some kind of interface.

This third possibility confers polymorphism to the return type of the factory method.

From this point on,

Each aforementioned orthogonal possibility can be mixed and matched to give rise to many interesting combinations; some of them are covered by the GoF book and others re-discovered by other gurus at later times.

Step two, encapsulation of multiple factory methods

Here, encapsulation simply means putting stuff into a class.

Encapsulation can have several meanings.

Information hiding - the usual meaning, but which I'm not concerned about that now.

Grouping of related methods into one place (a.k.a. cohesion). This will be explained here.

The factory method need not be the sole member of that class. You can have a class that has multiple factory methods. They can have different return signatures. They can return objects that belong to unrelated inheritance hierarchies.

It is you, the designer, who decrees that those two factory methods shall be united in one, and therefore you make them into a family.

Of course, a later accuser can come to you and complain that you shouldn't have put two unrelated factory methods under the same class. But the possibility is there; use it wisely.

Step three, making compatible factory methods interchangeable by making them a member of an interface.

To do this you must have multiple factory methods that share two commonality:

The arguments (or, the signature) to call these factory methods have identical types.

The return type of these factory methods belong to the same inheritance hierarchy.

If the commonality exists, you can create an interface with a method that has the signature and return type. Then, you can make these factory methods callable by a client which only knows this interface.

sorry but I must stop writing now...


问:
Is it acceptable to release a paid application to interface with an open-source backend?
I'm currently in development of an application that consists of two parts: PHP files that a user uploads to their own server, and a smartphone application.

Because the PHP files are going to reside on that person's server, I thought it would be beneficial to everyone that they might as well be open-sourced (Mozilla liscense or something of that effect).
These PHP files will extract data from the site, which can be read by anything that interfaces with it.

However, I intend to make an application that will read and edit this data, which will be a paid application and closed source.

Is this legal/ethical/a bad idea?

(Apologies for any mistakes, this is my first post on this exchange.)

答:
(I am not a lawyer, this is not legal advice, etc.)

My understanding says that this is perfectly fine.  A copyright license is a license from the copyright holder granting specific permissions under specific conditions.  It is up to the copyright holder what to license, to whom, under what conditions.  It is even common for the copyright holder to offer different people different licenses to the same code - that's called dual licensing.

In this case you might even be forced to it.  For example you might choose to make your server code under the http://www.gnu.org/licenses/agpl-3.0.html so that you can improve your odds of getting back any improvements in your server code.  But as examples like http://www.fsf.org/news/2010-05-app-store-compliance make clear, you cannot use that license on the itunes App Store.


问:
Passing parameters that need to be copied by value or const reference
I have a basic (mathematical) vector class, which in my opinion benefits from C++'s operator overloading. Vector-scalar operations are defined as self-modifying functions in the class itself,

```<code>class Vec3i {
  Vec3i& operator+=(int const n) {
    for (int i = 0; i < 3; ++i) {
      _data[i] += n;
    }
  }
  std::array<int, 3> _data;
};
</code>```

and as non-modifying free functions. For these I can see two options when it comes to passing in the vector.

```<code>// By value, meaning an implicit copy.
Vec3i operator+(Vec3i lhs, int const rhs) {
  return (lhs += rhs);
}

// By const reference, copying manually.
Vec3i operator+(Vec3i const& lhs, int const rhs) {
  auto result = lhs;
  return (result += rhs);
}
</code>```

Are there good reasons to prefer one variant over the other? I prefer having the const parameter (const-ing everything that will never be modified), but the by-value variant is nicely concise. Or should I simply start to read by-value as implicitly const?

答:
This is probably a bit opinionated, but if I see two equivalent alternatives in code, I typically prefer the one with less "noise". In your case, the difference of the second alternative to the first is only in additional "noise" - technical code which does not  improve the readability in any way. That is why I would prefer the first variant.

or should I simply start to read by-value as implicitly const

You should read functions with "by value" arguments as side-effect free, if that is what you meant.


问:
Use of for loop conditional statement unrelated to iterating variable
Is it considered decent form to write code like this:

```<code>int done = 0;
for (x = 0; !done; x++) {

    ... something involving 'x', that might end early ...

    if (!(x < max))
        done = 1;
}
</code>```

as opposed to having to use a while loop:

```<code>int done;
x = 0;
while (!done) {

    ... something involving 'x', that might end early ...

    if (!(x < max))
        done = 1;
    x++;
}
</code>```

or having to break out of a for loop:

```<code>for (x = 0; x < max; x++) {
    int done;

    ... something involving 'x', that might end early ...

    if (done)
        break;
}
</code>```

I prefer the first one, mainly because I dislike breaking out of loops, I prefer for loops, and it still looks neat. The second one appears to me as what others would likely use.

The third one feels icky to me, but it seemed like something else that others might use as opposed to the first.

What are the merits of using one over another? Should they each be used at different times, is one generally correct, or is it just a matter of personal preference?

答:
Different blocks have different meanings: by using the ones which are commonly used for a specific purpose, you make your code easier to read and maintain. By using the ones which are not commonly used for the purpose, you force readers of your code to stop and think why you've used this construct instead of the commonly used one.

While semantically correct, for (x = 0; !done; x++) is not something usual. while or do...while are used in situations where you need to break from a loop when a condition is met:

```<code>x = 0;
do {
    ... something involving 'x', that might end early.
    x++;
}
while (x <= max)
</code>```

(assuming that max can change within the loop; otherwise, you can simply do for (x = 0; x <= max; x++))

Being concise is important too. Less code means less risk of errors. For example, your while-based code is unnecessarily complicated. For example, (!(x < max)) takes time to understand and may be source of an error. The if block within the while adds complexity too. You also add a variable which transcends the while block and which can be simply removed.

I prefer the first one, mainly because I dislike breaking out of loops

That is your personal opinion which is valuable when you're working on a personal project which will never be shared with anybody. As soon as you think that the code may be open sourced (and actually read and used by others) or your work in a team, what you prefer may go against:

Your team habits. If in a team of 6 persons, 5 are using a construct and you are using a different construct, for the sake of consistency, do use the one your teammates use, including if yours looks clearly superior (unless of course you can convince your teammates at the beginning of the project that your's is better).

Community usages. Different communities use different styles, which leads to discrepancies between languages. For example:

```<code>if (something) {
}
</code>```

in JavaScript should be written:

```<code>if (something)
{
}
</code>```

in C#. Sticking to community usages makes it easier for the people outside your project to read your code (for example if you post a piece of code on Stack Overflow) or for you to read code from other projects.

Official style and style checkers. You may disagree with the choice the authors of the style guide made, but the fact is, consistency is more important.

For example, I find a few rules of PSR-2 quite weird. For example:

```<code>function hello()
{                      // Newline here.
    if (something) {   // No newline here.
    }
}
</code>```

Still, I'll rather use this style than create my own and find myself inconsistent with thousands of PHP programmers.

Body:
Different blocks have different meanings: by using the ones which are commonly used for a specific purpose, you make your code easier to read and maintain. By using the ones which are not commonly used for the purpose, you force readers of your code to stop and think why you've used this construct instead of the commonly used one.

While semantically correct, for (x = 0; !done; x++) is not something usual. while or do...while are used in situations where you need to break from a loop when a condition is met:

x = 0;
do {
    ... something involving 'x', that might end early.
    x++;
}
while (x <= max)

(assuming that max can change within the loop; otherwise, you can simply do for (x = 0; x <= max; x++))

Being concise is important too. Less code means less risk of errors. For example, your while-based code is unnecessarily complicated. For example, (!(x < max)) takes time to understand and may be source of an error. The if block within the while adds complexity too. You also add a variable which transcends the while block and which can be simply removed.

I prefer the first one, mainly because I dislike breaking out of loops

That is your personal opinion which is valuable when you're working on a personal project which will never be shared with anybody. As soon as you think that the code may be open sourced (and actually read and used by others) or your work in a team, what you prefer may go against:

Your team habits. If in a team of 6 persons, 5 are using a construct and you are using a different construct, for the sake of consistency, do use the one your teammates use, including if yours looks clearly superior (unless of course you can convince your teammates at the beginning of the project that your's is better).

Community usages. Different communities use different styles, which leads to discrepancies between languages. For example:

if (something) {
}

in JavaScript should be written:

if (something)
{
}

in C#. Sticking to community usages makes it easier for the people outside your project to read your code (for example if you post a piece of code on Stack Overflow) or for you to read code from other projects.

Official style and style checkers. You may disagree with the choice the authors of the style guide made, but the fact is, consistency is more important.

For example, I find a few rules of PSR-2 quite weird. For example:

function hello()
{                      // Newline here.
    if (something) {   // No newline here.
    }
}

Still, I'll rather use this style than create my own and find myself inconsistent with thousands of PHP programmers.


答:
I would go for the take by value approach.

Maybe in this case it does not matter as the Vec3i is cheap to copy, but in general, this would allow the lhs value to be constructed from rvalue with a move constructor, thus removing any copying of objects.

Title: Passing parameters that need to be copied by value or const reference

Body:
I have a basic (mathematical) vector class, which in my opinion benefits from C++'s operator overloading. Vector-scalar operations are defined as self-modifying functions in the class itself,

```<code>class Vec3i {
  Vec3i& operator+=(int const n) {
    for (int i = 0; i < 3; ++i) {
      _data[i] += n;
    }
  }
  std::array<int, 3> _data;
};
</code>```

and as non-modifying free functions. For these I can see two options when it comes to passing in the vector.

```<code>// By value, meaning an implicit copy.
Vec3i operator+(Vec3i lhs, int const rhs) {
  return (lhs += rhs);
}

// By const reference, copying manually.
Vec3i operator+(Vec3i const& lhs, int const rhs) {
  auto result = lhs;
  return (result += rhs);
}
</code>```

Are there good reasons to prefer one variant over the other? I prefer having the const parameter (const-ing everything that will never be modified), but the by-value variant is nicely concise. Or should I simply start to read by-value as implicitly const?


答:
Consider the following:

```<code>int done = 0;
for (i = 0; !done && i < max; ++i) {
    // ... something involving 'i', that might end early ...
}
</code>```

My personal preference here is to keep the "break condition" in one point.  If you add a second if clause that breaks, you risk to skip over that logic when you or another programmer reads over it later.  As a general rule, you should avoid using breaks in loops unless it is unavoidable.  In a certain sense, it is the equivalent of a goto.

In this way the number of lines is minimized and, dare I say it, the code looks cleaner this way.  Note that I used "i" in the place of "x" because if it is an index, as a rule, I tend to prefer i, though you can use whatever you prefer.

In general, if I have to cycle through a list or array of items, I will use a for loop, even if, as in your case, you may have conditional rules for exiting the loop.  I will use a while loop if I am iterating through a list or array of items and index/position in list or array is not important.  I will also use while if there is no predetermined end to the loop.  That doesn't mean there isn't one, but rather that I don't know when the while loop will end before I begin.

I will generally avoid do ... while as more often than not, the very reason you cannot continue due to your break condition is what the logic contained within will depend on, and so you usually end up with something like:

```<code>condition = 0;
do {
    if(!condition) {
       // Perform some operation and possibly set condition to 1.
    }
} while (!condition);
</code>```

I tend to at that point break the operation into a function of its own:

```<code>while(performOperation()) ;

...

int performOperation() {
    // Set result to value indicating success or failure
    return result;
}
</code>```

Hope that helps!

Title: Use of for loop conditional statement unrelated to iterating variable

Body:
Is it considered decent form to write code like this:

```<code>int done = 0;
for (x = 0; !done; x++) {

    ... something involving 'x', that might end early ...

    if (!(x < max))
        done = 1;
}
</code>```

as opposed to having to use a while loop:

```<code>int done;
x = 0;
while (!done) {

    ... something involving 'x', that might end early ...

    if (!(x < max))
        done = 1;
    x++;
}
</code>```

or having to break out of a for loop:

```<code>for (x = 0; x < max; x++) {
    int done;

    ... something involving 'x', that might end early ...

    if (done)
        break;
}
</code>```

I prefer the first one, mainly because I dislike breaking out of loops, I prefer for loops, and it still looks neat. The second one appears to me as what others would likely use.

The third one feels icky to me, but it seemed like something else that others might use as opposed to the first.

What are the merits of using one over another? Should they each be used at different times, is one generally correct, or is it just a matter of personal preference?

Body:
Consider the following:

int done = 0;
for (i = 0; !done && i < max; ++i) {
    // ... something involving 'i', that might end early ...
}

My personal preference here is to keep the "break condition" in one point.  If you add a second if clause that breaks, you risk to skip over that logic when you or another programmer reads over it later.  As a general rule, you should avoid using breaks in loops unless it is unavoidable.  In a certain sense, it is the equivalent of a goto.

In this way the number of lines is minimized and, dare I say it, the code looks cleaner this way.  Note that I used "i" in the place of "x" because if it is an index, as a rule, I tend to prefer i, though you can use whatever you prefer.

In general, if I have to cycle through a list or array of items, I will use a for loop, even if, as in your case, you may have conditional rules for exiting the loop.  I will use a while loop if I am iterating through a list or array of items and index/position in list or array is not important.  I will also use while if there is no predetermined end to the loop.  That doesn't mean there isn't one, but rather that I don't know when the while loop will end before I begin.

I will generally avoid do ... while as more often than not, the very reason you cannot continue due to your break condition is what the logic contained within will depend on, and so you usually end up with something like:

condition = 0;
do {
    if(!condition) {
       // Perform some operation and possibly set condition to 1.
    }
} while (!condition);

I tend to at that point break the operation into a function of its own:

while(performOperation()) ;

...

int performOperation() {
    // Set result to value indicating success or failure
    return result;
}

Hope that helps!


答:
In older C++ (pre C++11), there is no significant difference between your two implementations of operator+. Either the copy constructor gets called when you invoke the operator or when you make the explicit copy inside the operator.

In this case, it is more of a personal preference/coding guideline issue which one to choose.

With the introduction of move constructors in C++11, the pass-by-value case has gained an advantage, because that allows the parameter to be constructed using either the copy constructor or the move constructor, depending on what the operator is being invoked with.

For your Vec3i class, the difference is not that big, but if you have classes that maintain dynamically allocated resources, the proper use of move constructors can significantly reduce the amount of memory that your application needs.