问:
Is just using an email address for login a good idea?
Many a times I need to log into a website that I used months ago and have forgotten my password. So clicking the reset password link and the site sends me an email with a single use link which allows me to enter a new password and logs me in.

Happy days.

This got me thinking; how about we skip the whole password thing and just send a single use link in an email that I click which logs me into a month long session.

So, tell me.  Why wouldn't this work?

答:
It would work.  But it would be pretty aggravating to anyone who has graylisting set up on their mail server, which would delay your email for 15+ minutes.  And certainly you wouldnt want to be sending an unencrypted login link for a site that has any e-commerce purpose or stores personal information.

A better approach for you may be to use Social Login, and allow people to register and log in with their Facebook, Google, Yahoo, or other social network accounts.  I would never require the use of that, but as an option it removes the issues relating to forgotten user id's and passwords.


答:
This is a reasonable idea. Almost all passwords can be reset through email, and lots of users of many websites do this frequently, often every time or almost every time they log in (if it's a site that isn't used very frequently). If an attacker has control of your email the only advantages of using passwords rather than this method are:

It might take a little bit longer to reset passwords than to get hold of login tokens.

Security through obscurity - it might be less obvious which sites to get password resets from. You might not have any old password reset emails but you probably will have several old login tokens.

For anything that isn't important enough to need two-factor authentication at password reset, this is probably a good idea. It also adds some security, compared to resetting your password each time you use the site - it eliminates password guessing or bruteforcing and the problem of choosing string passwords.

One problem is probably although there are many forums, etc. that we log in to very infrequently, many of these websites believe or hope that we are going to use them all the time - no website wants to think they are the one we don't use much.

EDIT

It seems like some respondents have conceived this differently to how I have. I think the OP means that the link in the email would work only once, taking you to a page where you are considered to be logged in, and your browser can save cookies to that effect which last for one month. Therefore the old login emails saved in your client are not any use to an attacker - just as they can't use old password reset emails to re-reset your password. If you login on a different device, you have to re-request a login email, which then lets that browser instance be logged in.

ContentLicense: CC BY-SA 3.0

Title: Is just using an email address for login a good idea?

Body:
Many a times I need to log into a website that I used months ago and have forgotten my password. So clicking the reset password link and the site sends me an email with a single use link which allows me to enter a new password and logs me in.

Happy days.

This got me thinking; how about we skip the whole password thing and just send a single use link in an email that I click which logs me into a month long session.

So, tell me.  Why wouldn't this work?


答:
I guess a downside to that approach would be that the enduser would have to login to their email account every time they want to access your application.  Setting a month long session variable could also be a moot point if the user is on a public computer, or on a shared computer where two or more users of your application would be accessing the site.  It could require the enduser to have to check their email frequently if multiple accounts are accessing the app on the same machine.  I always feel like emails are a good idea for login credentials for two reason.

1) You can require the email to be unique to cut down on duplicate aliases, and the enduser will typically remember their email address a lot easier than a userID they created solely for your application.

2) It forces the enduser to input a valid email address as opposed to junk to access their account.  If they use a disposable email address to verify their account, they will no longer have access to it if they need to make any changes to their account in the future, so they will be reluctant to put a junk address in if the application is worthwhile.

Downsides are obvious.  It's annoying to have to input your email address (especially if it is on the longer side) for verification, but I've always felt that if the enduser will have an easier time recalling an email address for a login parameter as opposed to a userID established specifically for one application/site.  Hope this helps.  Just my two cents!


答:
First, your email isn't secure. Once a thief knows a certain website is sending out access links, they'll start paying closer attention.

Regardless of the format, this is no different than saving the username and password unprotected on the server. Whether it's a username & password combination or some lengthy and complex link string sent to your email address, it's not a good idea to store any of this on the server side in plain text (i.e. not salting & hashing).

Don't you feel more confident when the provider doesn't even have access to your password or whatever type of access link?

Edit: I guess the real question is why not keep sessions for a month.


问:
Should entities be accessible from all layers of an application?
I am googling this issue now for weeks, but cannot find a good discussion.
It boils down to this:
As POCO entities used in a dbContext are in fact a definition of the database, shouldn't they be constrained to the Data Access Layer and not be visible outside it?

On the other hand: it is convenient to hide some POCO entities in the ViewModels. so that changed properties can be passed back easily to the Data Access Layer.

I find many examples of Entities that make their way into the user interface, but also many examples of where AutoMapper is used to map the properties of a ViewModel to an Entity.

Can someone point me to some good working examples or discussions that could help me make a well informed choice?

答:
Here is one rule of thumb (but don't follow it blindly! Understand why you must use it!) for the direction that your dependencies must follow

Always depend in the direction of abstraction and stability

What that mean is that the dependencies that everyone depend on must be dependencies that change the less. Everyone depend on them, thus they're costly to change. So design those dependencies to have little to no reason to change!

And one way to do that is to make those dependencies mostly of unimplemented interface and stupid data structure that serve only to transfer information between objects. Then, more opinionated module, like the UI and the Data Access layer, and various part of the business logic, implements those interface with big fat objects that actually do the work. This is called the Dependency inversion principle.

Now, the direction that the arrow of the layers must take depend on who your talking to: "UI must depend on business logic which depend on the data access! No! The business logic must be in the center and everyone depends on it!" Lots of opinions and religion, but its all futile in the end. What matter is the abstraction. If your dependencies is through abstract elements, then you have it. The rest is pure pointless intellectual debate.

So, to answer your question, I'm gonna ask you another one "What are the reason for your so-called entity to change?" You have the answer in your own question :

As POCO entities used in a dbContext are in fact a definition of the database

If your entity are a definition of the database, that mean they will change everytime the database change. And if they must conform to a dbContext, that mean they have a strong coupling to the Entity Framework. If Microsoft decide to change the way EF work, your entities will have to change. Your entities will not be the nice little abstractions that you need to minimize coupling.

So yes, in that case, if you want to consider them a model of the database, then you should hide them away in a persistence layer, and make sure that nobody ever see them that don't also know about the database.

In summary, if you want an application that is well decoupled and strongly cohesive, no, they should not be depended upon by everyone, because if you do, everyone will depend transitively on the database structure. So everytime the database change, the whole application will have to change and it will be a pain. The way people usually cope with that is to make the database not change, and that introduce a lot of rigidity in your data storage. At some point or the other the database will need to change, and you will have to pay a hefty price of technical debt at that point.

The above was as neutral as I can make it, the rest will be more opinionated. Feel free to ignore it if it don't fit your views.

Your entities should be the base of your application and everyone should depend on them. They should not, never, be an implementation of the database. The entity framework job is to bend around your entity, and if he can't do that, then it's not the framework for you: ditch it as soon as you can. He shouldn't have any power over your entity. YOU decide how your entities are structured. Don't buy into the promise of magic that the conceptor demos are showing you. At one point or the other you will need to do something unexpected, all the magic will disappear, and you will have to leave your nice dreamy world and write the code you really needed from the start.

Try to make your entities an abstraction of your domain model (which is much less likely to change), and at that point, everyone will be able to depend on them, and your database will be free to be implemented however you want. You will have less magic at first and you will code more, but in the long shot, you will win on all account.


问:
Is Interactive the term for web application that respond quickly to user?
Just a quick question on Web Application attribute, if responsive (which mainly stems from web design) means website that adapts to different screen size, then the closest term I can find for Web Application which is highly 'responsive' to the user input (click, touch, etc.) is interactive? One might call it 'native-like' experience, or great user experience but I find these still too vague.

Well here is what I have at the moment:

Responsive Web Application refers to web applications which adopt responsive design, i.e. changes it layout on different screen sizes to increase user experience (supposedly).

Interactive Web Application refers to web application which has a lot interactivity to it, i.e. elements that can receive user inputs and reacts accordingly.

Native-like Web Application refers to web application that offers the same speed and performance as native application (either desktop software or mobile native apps).

I might have missed the right term, would love input on this?

答:
As a programmer, I interpret "interactive" to mean a web page that responds to the user without requiring a postback.  Postbacks are expensive; they require a round-trip to the server, and a re-rendering of the page.

As an example, consider an auto website that has the fields Year, Make and Model.  In a traditional, postback-style page, you would have to redraw the page each time you chose one of these fields, because the next field's dropdown list depends on the value the user selects from the previous field.  In modern web pages, you just AJAX updated dropdown values for the next field to the page, without requiring a postback.  This improves the user experience by improving the interactivity of the web page.

Similarly, Javascript can be used to create a high level of interactivity on a web page, because the Javascript is run locally in the browser, and not on the server after postback.


问:
I'm making a report generator, how should I run it?
So I've started a project to generate reports for our system. These are reports that we deliver to our end customers and they are so specialized that no existing system can generate them. This is not the problem however, the generator is working just fine.

For simpleness I've based it on an ASP.NET-solution that generates HTML that I squeeze through phantomjs to generate PDFs of the result. This also works fine. However, this is a one-shot operation. Right now I have a .BAT-file that runs phantomjs with a specific url, and this generates my PDF. However, I need to make some kind of queue-system, so the generation of reports is automatic when they are ordered.

The ordering-system is part of a legacy-system that is scheduled to be renewed, but "Not Right Now"(TM). So right now the orders are put in an SQL-table, with a "status"-column saying if it's generated or not. What I'm looking for are ideas for a system to run these reports, and maybe in the future even easily switch for a "real" queue based system (RabbitMQ or such).

I'm not locked to any language/framework as long as it's stable on windows, and can communicate with SQL Server. (I know C# and JS best). I was thinking of just making it with C#, but I'm not quite sure about the robustness of shelling out to phantomjs.. (I'm not sure about the robustness of shelling out to anything as a critical business operation ;) )

答:
Right now I have a .BAT-file that runs phantomjs with a specific url

Well, if that is your concern, why not avoid this batch file and run "phantomjs" through Process.Start? The robustness of such a solution will mainly depend on the correct error handling you implement (probably including time out handling etc.), and the way how you avoid file collisions when your queuing system starts running several pdf creation processes in parallel (make sure you use unique file names).

Furthermore, its perfectly possible to use the command shell for critical operations, but you have to implement full error handling there as well, which is somewhat harder than using  languages like C# or VB.NET.


问:
debugging web applications using debug parameter
A suggestion has been made by a team member to leave all debug code intact in our web pages... and then to create a variable that can be turned on / off to enable /
disable debugging.

This is a technique we use in some of our low level, non web code.
Just wondering if anyone had any comments on how they've implemented something similar for web applications?  Some of our web applications are written in lua, and others in PHP.

I like the idea and I've seen it used in different types of solutions.  However, my knee-jerk reaction is that for web apps, it might not be such a great idea.  I don't want to have a tonn of logs generated on the web server.
At the same time, it'd be nice to simply enable a variable and then start collecting information.

The alternative could be to always have a test page that calls the same methods that the production page does, but the test page dumps a bunch of data to the screen.

Just wondering if anyone has any experience / comments on doing this for the web as far as how to build it in, how difficult it is to maintain etc.
Thanks.

答:
We use such kind of debug versions or debug switches in all of our applications, be it desktop, server or web frontend, and over the years had good experiences with it.

Of course the amount of additional info varies between the environments. "Debug active" does not necessarily mean that you generate tons of huge log files. In fact, it has been turned out being more useful to have a different configuration switch for log verbosity.

The debug version typically contains all kind of internal consistency checks, some additional warnings and assertions, and also some additional information shown right in the UI. We integrate those information and checks that we find useful during development, test and even deployment, on the other hand we also do not hesitate to get rid of things that are not (or no longer) needed.

Key is, that the goal of a debug version is to actively support development and bug fixing, while a release version is intended to run fast and with a small footprint.


问:
What rationale is used when programming language designers decide what sign the result of modulo operation takes?
Going through Modulo operation (the avenue I entered while exploring the difference between rem and mod) I came across:

In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.

Questions:

Going through Euclidean division I found that remainnder of this operation is always positive (or 0). What limitation of the underlying computer hardware forces programming language designers to differ from mathematics?

Every programming language has it predefined, or undefined, rule according to which the result of the modulo operation gets it's sign. What rationale is adopted while making these rules? And if the underlying hardware is the concern then shouldn't rules change according to that, independent of programming language?

答:
For programming typically you want X == (X/n)*n + X%n; therefore how modulo is defined depends on how integer division was defined.

With this in mind, you're really asking "What rationale is used when programming language designers decide how integer division works?"

There are actually about 7 choices:

round to negative infinity

round to positive infinity

round to zero

several versions of "round to nearest" (with differences in how something like 0.5 is rounded)

Now consider -( (-X) / n) == X/n. I'd want this to be true, as anything else seems inconsistent (it's true for floating point) and illogical (a likely cause of bugs and also a potentially missed optimisation). This makes the first 2 choices for integer division (rounding towards either infinity) undesirable.

All of the "round to nearest" choices are a pain in the neck for programming, especially when you're doing something like bitmaps (e.g. offset = index / 8; bitNumber = index%8;).

That leaves rounding towards zero as the "potentially most sane" choice, which implies that modulo returns a value with the same sign as the numerator (or zero).

Note: You'll also note that most CPUs (all CPUs that I'm aware of) do integer division in the same "round to zero" way. This is likely to be for the same reasons.


问:
Best way to display domain object summary information efficiently and in an OO way from a large inheritance tree?
I've provided only simplified code as it's more of an abstract design question.

So I have many, many nested business/domain event objects, e.g.

```<code> public class Event
 {
  //bunch of properties and standard accessors
 }

 public class ExplosionEvent extends Event
 {
  //properties and standard accessors
 }
</code>```

And many more of these at different levels.  If I need information about any given object chosen, I display it in HTML like so

```<code> private String generateHTML(Event event)
 {
   StringBuilder sb = new StringBuilder();

   sb.append("<HTML><table>");//simplified

   sb.append("<TH>Time</TH>");
   sb.append("<TD>" + event.getEventTime() + "</TD>");

   if (event instanceof ExplosionEvent)
   {
     //append HTML and ExplosionEvent specific data
   }

   // ...many, many more calls like the one above

   sb.append("</table></HTML>");
 }
</code>```

As I have many event types, this means loads of duplicated HTML table tags and uses of instanceof so generateHTML is hundreds of lines long, split into methods of course but still, it's a lot of code that makes this hard to understand, navigate and therefore maintain.

This is ugly and I need a better design for this.  I had the idea of creating a method on Event which is overridable by all sub methods

```<code>//Using LinkedHashMap to preserve order as Properties wont do that
public LinkedHashMap<String, String> getAttributes()
{
 LinkedHashMap<String, String> list = new LinkedHashMap<String, String>();

 list.put("Time", eventTime);
}
</code>```

sub-classes then override this, call their parent and add date specific to them to the list meaning that no matter how many Event classes there is, the existing generateHTML method (external to Event objects) will then simply be one small loop

```<code>private String generateHTML(Event event)
{
  StringBuilder sb = new StringBuilder();

  b.append("<HTML><table>");

  for (Entry<String,String> entry : event.getAttributes().entrySet())
  {
    sb.append("<TH>" + entry.getKey() + "</TH>");
    sb.append("<TD>" + entry.getValue() + "</TD>");
  }

  sb.append("</table></HTML>");
}
</code>```

Is this putting too much logic in business/domain objects?

Is there a better way?

答:
This is a bad solution because it mixes two completely separate concerns - your objects' primary functions, and outputting its properties as HTML. On the other hand, I imagine you're trying to get access to the object's private state, which violates abstraction.

If you're only trying to print out this HTML for debugging purposes, the best solution would be to use reflection to inspect its fields/properties. If you only need to print out some fields, you can use annotations to mark which fields are meant to be inspected with reflection.

If providing access to its fields is part of the design then your classes should provide a your getAttributes as part of an interface, but delegate generateHTML to someone else. That way you don't have to change your classes just because you want to change the HTML formatting. You can decouple the code further by returning Map or Iterator from getAttributes instead of LinkedHashMap.

OwnerDisplayName: Ross Drew


问:
Three approaches for obtaining different sized versions of an image from the server
My android app needs different sized versions of images for different purpose and bandwidth preservation.

Approach one:

when the user uploads their avatar or another image, my php script creates 4 versions of that image: mini_200, medium_300, big_400 and original. those paths are then taken and stored in the database. Then, when I need the smallest image, I load it from http://myserver.com/item_images/200_mini_27304lkewsjfimage.jpg

Approach two:

same as approach one, but instead of adding prefixes to the names of the files, I store them in different folders - big, medium, mini. and in My app I just pass a parameter for which folder to look in

Approach three:

when the user uploads their avatar or another image, I only store the original. Then, when I need the smallest image, I load if this way: http://myserver.com/image_resizer.php?image="93_iosdfj0sd9fj.jpg"&new_width=200&new_height=200

Which one is better and why?
I feel like reinventing the wheel here, because this topic is too broad and I dont know where to read about it

答:
Your first two options are similar. In your second solution, since you could have two files with the same name in different folders, I would recommend using the size as a suffix in the file name such as images/mini/user_image_1482823_mini.jpg, images/large/user_image_1482823_large.jpg.

Your third approach has an advantage in that it uses less disk space than the other two as well as not needing to manage sets of files and variants for all images, but it must resize images in the fly. This has the potential to cause performance problems if the source images are very large and there are many requests coming in for many different images of different sizes. You could deal with that by caching commonly requested images at different sizes. This may add a bit of complexity the overall architecture of the system, but could be a very good solution if implemented properly.

Since all of this activity would be happening on the server side, I don't thin it would affect your app too much. Your app would only ever submit one image and receive one image. Right?


答: It sounds like your third option is the simplest and requires the least storage, but is potentially also the slowest because the server will end up generating the same files over and over. Start with that method, but be prepared to switch to the first or second option if and when you find that the server is becoming taxed. </p>

Title: Three approaches for obtaining different sized versions of an image from the server

Body:
My android app needs different sized versions of images for different purpose and bandwidth preservation.

Approach one:

when the user uploads their avatar or another image, my php script creates 4 versions of that image: mini_200, medium_300, big_400 and original. those paths are then taken and stored in the database. Then, when I need the smallest image, I load it from http://myserver.com/item_images/200_mini_27304lkewsjfimage.jpg

Approach two:

same as approach one, but instead of adding prefixes to the names of the files, I store them in different folders - big, medium, mini. and in My app I just pass a parameter for which folder to look in

Approach three:

when the user uploads their avatar or another image, I only store the original. Then, when I need the smallest image, I load if this way: http://myserver.com/image_resizer.php?image="93_iosdfj0sd9fj.jpg"&new_width=200&new_height=200

Which one is better and why?
I feel like reinventing the wheel here, because this topic is too broad and I dont know where to read about it


问:
What is best software design in creating methods?
I had created a extension method which extended the string type in C#.

```<code>// actually checks if the string is empty or null and then looks up the default
// promotion code which is set in the backend admin system.
promocode.HasPromode();
</code>```

I thought that was fine and dandy, but another colleague thought I should inject the method
through constructor injection, which should implement a interface. I think this is overkill to have a simple lookup function to do that.

Another colleague thought that extending the string type makes it simpler to use it wrong and exposes it for the wrong purposes.

Which one is right? All solutions work fine; but some of these solutions should be the best one, or does it matter actually? It should matter, because we are having those discussions and we're trying to make the code better.

答:
The problem that I have with your method is that it ties a method to the string class that has nothing to do with strings in general.

It would make more sense if your extension method had something to do with strings in general, not a particular field.  IsPalindrome() would make more sense as an extension method on string than HasPromode() [sic], because IsPalindrome() is applicable to any string.

Now, then...

Another colleague thought I should inject the method through constructor injection, which should implement a interface.

Er, what?

This fellow sounds like an Architecture Astronaut.  While his suggestion might make sense in some context, a simple Enum.TryParse() call would suffice.

```<code>PromoCode outValue;
if (Enum.TryParse(promoCode, out outValue))
{
    // string contains valid promo code.
}
</code>```

Body:
The problem that I have with your method is that it ties a method to the string class that has nothing to do with strings in general.

It would make more sense if your extension method had something to do with strings in general, not a particular field.  IsPalindrome() would make more sense as an extension method on string than HasPromode() [sic], because IsPalindrome() is applicable to any string.

Now, then...

Another colleague thought I should inject the method through constructor injection, which should implement a interface.

Er, what?

This fellow sounds like an Architecture Astronaut.  While his suggestion might make sense in some context, a simple Enum.TryParse() call would suffice.

PromoCode outValue;
if (Enum.TryParse(promoCode, out outValue))
{
    // string contains valid promo code.
}


答:
You do not want to store static images within a GET query (i.e. a URL with a "?"), as most HTTP caches will not hold on to the results.

An improvement on option 3 would be to use custom routing so that a path like "/images/large/foo.gif" gets interpreted on the server as something like "/resize_image?size=large&name=foo.gif" (see your specific programming language, library framework and web server for details).

A further benefit of this mechanism is that you're now using a regular path structure that's easily shared between options #2 and #3 - the only difference is server-side configuration.  That gives you the flexibility to trade off storage space and CPU time to obtain the best balance possible for your application.


答:
I agree with Robert Harvey on everything except the solution.  This is mainly because, more than likely your promotion codes are stored in the database and could change.  In this case, I wouldn't opt for an enum simply because any additions/changes to the list of available promotion codes would require a build in order to update the enum with the correct values.

Instead, I would opt for a solution like this:

```<code>public class PromotionCodeManager //or some other meaningful name
{
    public bool IsPromotionCode(string value)
    {
        //TODO Attempt to lookup the promotion code in the backend system
        //and return true if it's a valid promotion code that hasn't expired.
    }
}
</code>```

And, if you want to get really fancy and satify the desires of your architecture astronaut, you could use dependency injection in the constructor of this class which would take an IPromotionCodeRepository that the class would use to lookup the valid promotion codes and determine if the value passed in is valid.

Then, the client code could look something like this:

```<code>if (new PromotionCodeManager(promotionCodeRepository).IsPromotionCode(myValue))
{
    //Valid promotion code
}
else
{
    //Invalid promotion code
}
</code>```

Title: What is best software design in creating methods?

Body:
I had created a extension method which extended the string type in C#.

```<code>// actually checks if the string is empty or null and then looks up the default
// promotion code which is set in the backend admin system.
promocode.HasPromode();
</code>```

I thought that was fine and dandy, but another colleague thought I should inject the method
through constructor injection, which should implement a interface. I think this is overkill to have a simple lookup function to do that.

Another colleague thought that extending the string type makes it simpler to use it wrong and exposes it for the wrong purposes.

Which one is right? All solutions work fine; but some of these solutions should be the best one, or does it matter actually? It should matter, because we are having those discussions and we're trying to make the code better.

Body:
I agree with Robert Harvey on everything except the solution.  This is mainly because, more than likely your promotion codes are stored in the database and could change.  In this case, I wouldn't opt for an enum simply because any additions/changes to the list of available promotion codes would require a build in order to update the enum with the correct values.

Instead, I would opt for a solution like this:

public class PromotionCodeManager //or some other meaningful name
{
    public bool IsPromotionCode(string value)
    {
        //TODO Attempt to lookup the promotion code in the backend system
        //and return true if it's a valid promotion code that hasn't expired.
    }
}

And, if you want to get really fancy and satify the desires of your architecture astronaut, you could use dependency injection in the constructor of this class which would take an IPromotionCodeRepository that the class would use to lookup the valid promotion codes and determine if the value passed in is valid.

Then, the client code could look something like this:

if (new PromotionCodeManager(promotionCodeRepository).IsPromotionCode(myValue))
{
    //Valid promotion code
}
else
{
    //Invalid promotion code
}


问:
How do I effectively address code-review feedback about class and method names without a suggestion for a better or alternate name?
Part of code review feedback is suggesting better names for methods and classes. How can I address feedback about class and method names which does not suggest an alternative?

For example, I might create the class

```<code>public class FooBar { }
</code>```

My reviewer would then say, "Try to think of a better name than this." or "This name isn't helpful." without suggesting an alternative name.

I have already thought through the class name and FooBar is really the best I can come up with. How can I actually address the feedback from this review?

答:
You have two problems.  One is that you have difficulty naming things.  The other is that you have difficulty communicating about precisely what is wrong with a name.  Your colleagues reviewing the code may share this difficulty, or they may be assuming the precision isn't needed because they think you can figure it out on your own.  Either way, learning about naming in a more objective way will help you not only with naming, but with the communication aspect as well.

There are books with entire chapters on the topic of naming, and multitudes of websites discussing those chapters.  Check out Clean Code, Code Complete, and Refactoring and do google searches like "Clean code naming."  Naming is certainly a skill that can be improved using objective measures.

A very high-level summary of Clean Code from the table of contents:

Use intention-revealing names. For example, elapsedTimeInDays instead of d.

Avoid disinformation.  For example, don't use accountList if it's not a List.

Make meaningful distinctions. For example, don't use ProductInfo and ProductData to mean different things.

Use pronounceable names.

Use searchable names.  No single-letter names (except as locals in short methods) or numeric literals.

Avoid encodings like hungarian, etc.

Avoid mental mapping.  Don't make the programmer translate to the real meaning in his head.

Classes should have noun or noun phrase names.

Methods should have verb or verb phrase names.

Don't be cute.

Pick one word per concept.  For example, don't have fetch, retrieve, and get mean the same things in different classes.

Don't pun. For example, don't use add to mean different things in different classes.

Use terms programmers are familiar with, like pattern names.

Use terms that are familiar to people who know the problem domain.

Add meaningful context. For example, use addressState instead of just state if you can't easily tell what kind of state it is from the context.

Don't add gratuitous context. For example, accountAddress and customerAddress are good names for instances, but not for classes, which should just be named Address.


问:
Single product owner for multiple Scrum teams
Is that a common practice to have a single product owner for more than one Scrum team, or usually you have a product owner for each team (even if multiple teams work on the same product).

Thanks

答:
The product owner should be the foremost business/user base expert for the application you're building.  Each product should have one product owner, however this is not always the case in practice.  Sometimes, you may have 2-3 product owners if there are several people from different departments driving the project.

In any case, the product owner or owners are associated to a single product.  Therefore, if you have more than one team working on the same product, the product owner(s) will be the same for each team of said product.

Since each product should have its own product owner(s), teams working on different products could have different product owner(s).


答:
This is a communication issue between you and the reviewer. A code review is not a one sided "you will do it this way or else" discussion of code. It is a chance for several other developers at your site to see what, if anything, could use improvement. As often as not, during code reviews of other developer's code, I learn something new.

If your reviewer doesn't have a concrete example of how the name of your class/function/method could be named, then they don't belong in the review. Ask the reviewer for an example that would be appropriate.

If you are the reviewer and don't know what the routine is doing, ask the developer what the code does from a high level perspective. Lead/coach them to an answer that is acceptable for you both.

In either case, it should be a discussion point that as a reviewer you lead or as the reviewed you instigate.

Title: How do I effectively address code-review feedback about class and method names without a suggestion for a better or alternate name?

Body:
Part of code review feedback is suggesting better names for methods and classes. How can I address feedback about class and method names which does not suggest an alternative?

For example, I might create the class

```<code>public class FooBar { }
</code>```

My reviewer would then say, "Try to think of a better name than this." or "This name isn't helpful." without suggesting an alternative name.

I have already thought through the class name and FooBar is really the best I can come up with. How can I actually address the feedback from this review?


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答: You can support it to get money.  If you have a program that is very well thought of and used by the community, say like jboss, you can offer your services and support.  People will pay for it.</p>

Title: Why develop free, open source programs?

ContentLicense: CC BY-SA 2.5


问:
Engineering a better solution, coming from existing codebase
The Code

I have high-business-value daily-used-by-customer software that is written in PHP and spans approximately 600K lines of code.

Customer for a long time needs, wants, and demands new features and functionality.  The time to have it done is yesterday.  So, just write the new features and implement new functionality and deliver it to the customer, yes?  Well, no, here are some problems that have been causing considerable pain to current developers:

Existing code-base is ... a big ball of mud.

Notable problems:

code is hairy - a single feature permeates everything, tracing code is a pain, and adding a feature may potentially impact everything else

there are no tests

mix of procedural and object oriented code ridden in bad programming practices

files reaching 6000-lines of HTML, CSS, PHP, SQL, jQuery, JavaScript, comments

complete disregard/non-existence of MVC/separation-of-concerns pattern. Code is intermixed together

some business logic depends on volatile things that have no relation to the code (like database metadata)

hardcoded values, paths, and lack of configurability contribute to lack of security of current architecture

large repeated blocks of essentially the same code contribute to similar features working slightly differently.  Updating one does not update the other

code is slow, lack of documentation., etc, etc.  quite a few other things can be done better

It works...

The good thing is that it works...  The functionality that's there, is reasonably worked-out for actual business cases, but ... going forwards is painful.

The Problem

It is easier now (and faster) to add a new feature using existing code style, mostly using cut-n-paste-n-modify approach, thus perpetuating the badness, than it is to do rewrites of this thing using currently existing modern best practices.

Solution?

There is a talk about rewriting the whole thing using one of the currently-leading frameworks (i.e. ZF2), but in doing so it means ignoring customer demands, taking a long time to build the software, and essentially creating new software (version 0.0.1) for the customer, with all the new-software bugs and lack of mature-software feel and functionality.

Another thought is to do some incremental development.  i.e. When a new feature comes about, write it using a new approach.  This is currently failing for the reason stated under "The Problem" title above.

Yet another idea is to do some slow refactoring of existing codebase... It might work in cleaning up things like MVC and a host of other things, and it will take a long time, and it will essentially feel like unraveling a messed up tightly-wound knotted ball of yarn.  But doing this will not address things like unit testing, dependency injection, modern framework principles, and so on.

So, in the end, new features are coming, code is being added, and the existing codebase is not getting any better.  What might you suggest to do in this case?

答: I'm in a similar situation, if well in a completely distinct technology stack, and in my case (and I guess that also in yours) it is quite obvious that a whole rewriting of production code is not an option, due to practical limitations. That makes the most sense is taking it in small steps. When you are required to introduce a new feature, you do it in a more manageable way; when you have to modify an existing module/class/method/whatever, you take the opportunity and refactor it. Always try to end up with a better code, if perhaps at the expense of reducing your velocity a little in order to get some slack to pay your debt. Also, if you can silently introduce a framework that can be helpful in the long run, while coexisting with the current mud, consider it.</p>


答:
But doing this will not address things like unit testing, dependency injection, modern framework principles, and so on.

Why not?
You do not need to unit test everything - just around what you change/refactor. And if you test that, you'll progressively add mocks and DI.

I strongly recommend Michael Feather's book: Working effectively with legacy code, as it describes that problem and solutions quite well.

Title: Engineering a better solution, coming from existing codebase

Body:
The Code

I have high-business-value daily-used-by-customer software that is written in PHP and spans approximately 600K lines of code.

Customer for a long time needs, wants, and demands new features and functionality.  The time to have it done is yesterday.  So, just write the new features and implement new functionality and deliver it to the customer, yes?  Well, no, here are some problems that have been causing considerable pain to current developers:

Existing code-base is ... a big ball of mud.

Notable problems:

code is hairy - a single feature permeates everything, tracing code is a pain, and adding a feature may potentially impact everything else

there are no tests

mix of procedural and object oriented code ridden in bad programming practices

files reaching 6000-lines of HTML, CSS, PHP, SQL, jQuery, JavaScript, comments

complete disregard/non-existence of MVC/separation-of-concerns pattern. Code is intermixed together

some business logic depends on volatile things that have no relation to the code (like database metadata)

hardcoded values, paths, and lack of configurability contribute to lack of security of current architecture

large repeated blocks of essentially the same code contribute to similar features working slightly differently.  Updating one does not update the other

code is slow, lack of documentation., etc, etc.  quite a few other things can be done better

It works...

The good thing is that it works...  The functionality that's there, is reasonably worked-out for actual business cases, but ... going forwards is painful.

The Problem

It is easier now (and faster) to add a new feature using existing code style, mostly using cut-n-paste-n-modify approach, thus perpetuating the badness, than it is to do rewrites of this thing using currently existing modern best practices.

Solution?

There is a talk about rewriting the whole thing using one of the currently-leading frameworks (i.e. ZF2), but in doing so it means ignoring customer demands, taking a long time to build the software, and essentially creating new software (version 0.0.1) for the customer, with all the new-software bugs and lack of mature-software feel and functionality.

Another thought is to do some incremental development.  i.e. When a new feature comes about, write it using a new approach.  This is currently failing for the reason stated under "The Problem" title above.

Yet another idea is to do some slow refactoring of existing codebase... It might work in cleaning up things like MVC and a host of other things, and it will take a long time, and it will essentially feel like unraveling a messed up tightly-wound knotted ball of yarn.  But doing this will not address things like unit testing, dependency injection, modern framework principles, and so on.

So, in the end, new features are coming, code is being added, and the existing codebase is not getting any better.  What might you suggest to do in this case?


问:
Testing all combinations
I need to do some performance measurements inside my application. I want to measure, change some parameters, measure again. There are different algorithms I want to test, and there are various parameters which interact with each other in that the total performance depends on all of the parameters (but the parameters themselves don't influence each other. e.g. if I set x to 5, it will always stay 5 and changing some other parameter won't change x).

I think the total number of combinations is quite high, at least enough so that I don't want to manually change everything and test out each possibility by hand.

I'm looking for a piece of lightweight piece of software architecture (I dare say a design pattern) that basically enables me to define a set parameter types relevant to an algorithm, the possible values of those types, and that piece of code should then run through all combinations of those types and their values, for each one doing the required stuff (calling some functions to change values, etc.) and then executing the algorithm.

Example: An algorithm depends on values x, y and z. x can be either 0 or 1, y can be "hello" or "goodbye", and z can be in the range [0,100]. The solution I'm looking for starts with [0,"hello",0], calls some functions to set the values of those variables, lets the profiling run for some time, then changes to [0,"hello",1], repeat, [0,"hello",2]... etc.

This is probably something that people have needed to solve before. How do I solve this elegantly?

答:
You can do this in (at least) two ways.

One is simply to have a vector with the cardinalities of your parameters. So since your parameter array is (slightly edited to get unique numbers):

```<code>[
    [ 0, 1, -1 ],
    [ 'hello', 'goodbye' ],
    [ 0 .. 100 ],
]
</code>```

the cardinalities are [ 3, 2, 101 ]. This gives a Cartesian product of 3*2*101 = 606 combinations. Given any number from 0 to 605 inclusive, its remainder modulo 3 is the index of the parameter in the first option array, then modulo 2 again for the second, and modulo 101 for the third.  E.g. 137:

137 modulo 3 is 2, so first parameter is -1.
   137 integer-divided-by 3 is 45, 45 modulo 2 is 1, so second parameter is "goodbye".
   45 i.d.b. 2 is 22, so third parameter is 22.

This allows for mapping the whole configuration to a single number and viceversa. Then you can have a function or method that will set the configuration from a number, given the arrays of possible values.

You can now just try all the values in sequence. This is just a brute force approach.

Another possibility is to assume that the performance function f(x, y, z) is reasonably continuous, i.e., the change in performances is proportional to the change of any given parameter from its i-th to i+j-th value; the more you change, the more performances will vary.

If this holds true, there are several options to find the performance maximum efficiently, without examining all the possible values. For example, you generate a number at random from 0 to (here) 605, thus obtaining an initial configuration (x, y, z). You can now increase or decrease any of the three parameters, which gives you at most twenty-seven sets of values to investigate (each parameter can increase by one, decrease by one or stay the same, which is three possibilities; and three are the parameters, so you raise the number of possibilities by the number of parameters and get 3^3 or 27). Run the performance test for each of these sets. The best combination will be your new starting point. Repeat (you will want to cache results for the last runs, since several sets would otherwise be examined repeatedly).

When you have many possible values for each parameter, this method allows for examining comparatively very few of them. If f() is "reasonably" well-behaved, this method will "walk" the parameter space following the line of steepest ascent, rapidly converging towards the best combination. You may want to use techniques such as annealing or restarting from a very different initial position to ensure that you do not get "stuck" in a local maximum.

Title: Testing all combinations

Body:
You can do this in (at least) two ways.

One is simply to have a vector with the cardinalities of your parameters. So since your parameter array is (slightly edited to get unique numbers):

[
    [ 0, 1, -1 ],
    [ 'hello', 'goodbye' ],
    [ 0 .. 100 ],
]

the cardinalities are [ 3, 2, 101 ]. This gives a Cartesian product of 3*2*101 = 606 combinations. Given any number from 0 to 605 inclusive, its remainder modulo 3 is the index of the parameter in the first option array, then modulo 2 again for the second, and modulo 101 for the third.  E.g. 137:

137 modulo 3 is 2, so first parameter is -1.
   137 integer-divided-by 3 is 45, 45 modulo 2 is 1, so second parameter is "goodbye".
   45 i.d.b. 2 is 22, so third parameter is 22.

This allows for mapping the whole configuration to a single number and viceversa. Then you can have a function or method that will set the configuration from a number, given the arrays of possible values.

You can now just try all the values in sequence. This is just a brute force approach.

Another possibility is to assume that the performance function f(x, y, z) is reasonably continuous, i.e., the change in performances is proportional to the change of any given parameter from its i-th to i+j-th value; the more you change, the more performances will vary.

If this holds true, there are several options to find the performance maximum efficiently, without examining all the possible values. For example, you generate a number at random from 0 to (here) 605, thus obtaining an initial configuration (x, y, z). You can now increase or decrease any of the three parameters, which gives you at most twenty-seven sets of values to investigate (each parameter can increase by one, decrease by one or stay the same, which is three possibilities; and three are the parameters, so you raise the number of possibilities by the number of parameters and get 3^3 or 27). Run the performance test for each of these sets. The best combination will be your new starting point. Repeat (you will want to cache results for the last runs, since several sets would otherwise be examined repeatedly).

When you have many possible values for each parameter, this method allows for examining comparatively very few of them. If f() is "reasonably" well-behaved, this method will "walk" the parameter space following the line of steepest ascent, rapidly converging towards the best combination. You may want to use techniques such as annealing or restarting from a very different initial position to ensure that you do not get "stuck" in a local maximum.


问:
Thread safe GUI programming
I have been programming Java with swing for a couple of years now, and always accepted that GUI interactions had to happen on the Event Dispatch Thread. I recently started to use GTK+ for C applications and was unsurprised to find that GUI interactions had to be called on gtk_main. Similarly, I looked at SWT to see in what ways it was different to Swing and to see if it was worth using, and again found the UI thread idea, and I am sure that these 3 are not the only toolkits to use this model. I was wondering if there is a reason for this design i.e.  what is the reason for keeping UI modifications isolated to a single thread. I can see why some modifications may cause issues (like modifying a list while it is being drawn), but I do not see why these concerns pass on to the user of the API. Is there a limit imposed by an operating system? Is there a good reason these concerns are not 'hidden' (i.e. some form of synchronization that is invisible to the user)? Is there any (even purely conceptual) way of creating a thread safe graphics library, or is such a thing actually impossible?

I found this http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness which seems to describe GTK differently to how I understood it (although my understanding was the same as many people's) How does this differ to other toolkits? Is it possible to implement this in Swing (as the EDT model does not actually prevent access from other threads, it just often leads to Exceptions)

答: BeOS implements a GUI via a separate thread per widget, with the result of amazingly good responsiveness on very primitive hardware by modern standards (I noticed very little lag in everyday use of my developer BeBox with dual 66 MHz Power 603s and 64 Mb of RAM back in 1999).  Safety of concurrent memory was obviously a major concern and the OS developers did a number of different innovative tricks to keep threads from stepping on one another's memory.  This is a nice overview.</p>

Title: Thread safe GUI programming


答:
run through all combinations of those types and their values, for each one doing the required stuff (calling some functions to change values, etc.) and then executing the algorithm.

That sounds like Cartesian Product to me. Many languages have library to calculate the Cartesian Product of a list of lists, e.g python itertools.product().

@Iserni had a very good point, in most cases, the performance of algorithms aren't completely random. There are often ways to avoid doing exhaustive search, maybe at the cost of possibly not finding the most optimal solution (i.e. a heuristics).

Title: Testing all combinations

Body:
I need to do some performance measurements inside my application. I want to measure, change some parameters, measure again. There are different algorithms I want to test, and there are various parameters which interact with each other in that the total performance depends on all of the parameters (but the parameters themselves don't influence each other. e.g. if I set x to 5, it will always stay 5 and changing some other parameter won't change x).

I think the total number of combinations is quite high, at least enough so that I don't want to manually change everything and test out each possibility by hand.

I'm looking for a piece of lightweight piece of software architecture (I dare say a design pattern) that basically enables me to define a set parameter types relevant to an algorithm, the possible values of those types, and that piece of code should then run through all combinations of those types and their values, for each one doing the required stuff (calling some functions to change values, etc.) and then executing the algorithm.

Example: An algorithm depends on values x, y and z. x can be either 0 or 1, y can be "hello" or "goodbye", and z can be in the range [0,100]. The solution I'm looking for starts with [0,"hello",0], calls some functions to set the values of those variables, lets the profiling run for some time, then changes to [0,"hello",1], repeat, [0,"hello",2]... etc.

This is probably something that people have needed to solve before. How do I solve this elegantly?


问:
When is it NOT good to use actors in akka/erlang?
I've been working with akka for 7-8 months now daily.
When I started, I would be working on applications and notice that actors would be used basically anywhere once inside the actor system for communicating between most objects. So I did the same - spin up another actor for x/y/z.

It seems to me that this may be too indiscriminate, adding complexity where it isn't needed - but I can't find any discussions on where actors vs plain synchronous or even async logic via futures should be used. I started pondering my stance after my coworker mentioned something similar. I realized several cases more recently where I have pondered a task and then avoided creating another actor because I could achieve the same result safely in an immutable implementation - eg something like getting configuration values from a db or file somewhere where you access very infrequently and will wait for the result is the actual use case.

In particular, it seems to me that any case where you're playing with immutable state, actors create complexity and limit throughput - a pure function in an object, for example, can be called concurrently with no risk with any level of concurrency, yet an actor can only process one message at a time. The alternate consideration is you'll park the thread if you need to wait for the result unless you start using futures but cases where you don't need to worry about async messaging or scale it seems it may be overkill to employ an actor.

So my question is - is there a bad time to use actors? I'm curious how erlang looks and would really like other people's insight. Or if there are some principles around actor use.

答:
This is a question I am interested in and I have been doing some research on. For other viewpoints, see this blog post by Noel Walsh or this question on Stack Overflow. I have some opinions I would like to offer:

I think Akka, because it works with messages, encourages a "push mindset". Often, for concurrency, I would argue this is not what you want. Pull is much safer. For example one common pattern for distributed systems is to have a set of workers processing information in a queue. Obviously this is possible in Akka but it doesn't necessarily seem to be the first approach people try. Akka also offers durable mailboxes but again it depends how you use them - a single shared queue is a lot more flexible than per worker queues for balancing / re-assigning work.

It's easy to get into the mindset of replacing your classes with actors. In fact some people even seem to advocate it by saying actors should only do one thing. Taken to it's logical conclusion this increases code complexity as Jason describes, because if every class is an actor, that's a lot of extra messages and receive / send blocks. It also makes it harder to understand and test the code because you lose the formality of interfaces - and I am not convinced that comments are a solution to this. Also despite Akka's legendary efficiency, I suspect that actor proliferation is not a good idea performance wise - when we use Java threads we know they are precious and conserve them accordingly.

It's related to the previous point, but another annoyance is the loss of type information that Noel and Pino highlight, as for many of us that's why we are using Scala rather than other languages such as Python. There are some ways around this but they are either non-standard, not recommended or experimental.

Finally concurrency, even if you have a "let it crash" mindset, is hard. Alternative programming models can help but they don't make the problems go away - they change them - that's why it's good to think about them formally. It's also why Joe Average developer reaches for ready built tools like RabbitMQ, Storm, Hadoop, Spark, Kafka or NoSQL databases. Akka does have some prebuilt tools and components, which is cool, but it also feels quite low level, so more ready built common elements of distributed systems would help developers and ensure systems are built right.

Like Jason, I am keen to hear other people's insight here. How can I address some of the issues above and use Akka better?

ContentLicense: CC BY-SA 4.0


问:
Socket Connection Data Insert
I have been working through a high-performance application where I have identified a bottleneck. The bottleneck is actually when the application must insert messages from a socket, it will record them in a database. The trouble is the speed at which the messages come through are so fast that the application cannot catch up due to poor architectural planning. Clearly, insertion needs to be improved.

So here's the question: What is the most optimal format for performing inserts of individual records?

I have looked over at this link on high performance inserts revision 4 and found that doing something of this nature would require an extensive restructure in the application compared to its current attempt at concatenating a string together such as this:

```<code>INSERT INTO table (col1,col2,col3) VALUES (val1,val2,val3),(val4,val5,val6),(val7,val8,val9)
</code>```

Does anybody have any have an insight over which is better, datatable insertion vs string concatenation?

答:
Well, thanks for anybody who might have read this and considered what to do but I decided to try and restructure the application because I am running out of time.

Winner by a mile: DataTable insertion as stored procedure parameter

Concatenating strings only allowed me to create and send about 750 records at a time when it caused the application to slow down enough to get overwhelmed and throw an exception. Using a datatable insertion described in the link allowed me to safely go way above 3,000 records at a time. Knock on wood, my application has not crashed yet during testing. It seems like I can drink from a fire hose.

Just to put some stats around it, my table had 18 million records before I revised the application. In approximately 1 hour, I have inserted 1.3 million more records coming from the socket one at a time. It feels like the method could take a lot more than I am currently testing it with.

Title: Socket Connection Data Insert


问:
Things to consider for inviting and restricting users to a beta website
What are the best practices for designing a workflow for inviting users to a beta website? This is not for any specific programming language. 2 main requirements are

An interested user can request for an invite using her email

A signed up user can invite others via email (or social media
maybe?).

My thoughts:

In case#1, on submit, generate a reversible hash of the email and the timestamp of submission.

Then, send an email with the hash as a query param. When someone clicks on the URL, the controller/router should decrypt the hash and validate the timestamp. If valid, check if the user already exists, else, forward to the sign up page with the email id field pre-populated (or frozen), and allow the user to enter & confirm password and other details.

If the timestamp had expired, send another email to the same user with a new hash.

Case#2, should be exactly similar, but instead of the interested user, an existing user fills up the invitation form, and the email sent to the interested user will have the email or name of the existing user.

Are there any security concerns in this approach? Are there any approaches that would provide a better UX?

答:
User Experience

In terms of the user experience, you have it down:

User requests invitation

Someone or a process grants the invitation and an e-mail is sent to the user

User clicks a link, is asked to enter sign-up details

For referral sign-ups:

User requests invitation for another user

Other user is automatically granted invitation and sent e-mail

Other user clicks a link, is asked to enter sign-up details

Implementation

In terms of implementation, however, you lost me at "reversible hash".

In short, I'd use a one-time token (arbitrary string) for the invitation validation, and have a table to store the invitations.

The table would look something like:

InvitationId - identity

Email - string

Created - datetime

Token - string

Expiry - datetime

The two processes are actually quite similar, so I'll cover both pieces together.

1. Invitation request

User enters their e-mail, requesting an invitation, or as an existing user, enters an e-mail for another user.

In either case, this would make a new entry in the invitations table, populating the Email and Created fields.

In the case of an existing user sending an invitation, it would immediately invoke the next part:

2. Granting invitation

When someone or some process decides to grant the invitation, it would do two things:

Generate a random token and Expiry date and update the table

Send an e-mail containing a sign-up URL with the token

There are many ways to generate a random token, but something simple could be the the sha1 of a Guid, so you end up with something like 1bde8e3ed5709cb399cff0e910442d9b99e181fb.

You'd then send the link as https://mysite.com/signup?token=1bde8e3ed5709cb399cff0e910442d9b99e181fb

3. Signup

The first thing to do, of course, is validate the received token: does it exist and hasn't yet expired?

If everything is good, then you allow the user to sign up, and upon completion, remove the invitation entry.

Additional notes

The token-based approach is much more secure, since it cannot be "cracked". Someone would have to use brute force to guess every possible token, and you could mitigate that by locking the e-mail address for the rest of the sign-up to the one in the invitation.

Keeping this separate from what will eventually be the "non-beta" signup process is also clean in terms of coming out of beta: you should be able to remove this table and related code fairly easily, in contrast to having extra fields stored with the regular user accounts. Think of the token more like a permission to create a new user entry.

I tend to not implement more than is necessary, and not knowing your use case it's hard to speculate on some other things you might want to implement:

You may want to keep invitations for some reason (reporting?), so you could use a status field or something similar, and/or date fields indicating the various actions

You may wish to re-send e-mails, and so it may be useful to store fields indicating when e-mails were sent (and how many)

You may wish to track sign-up source (eg, direct from a URL, or another user) and you could store that in an additional field when you create the invitation entry, and perhaps even transfer it to the account once they sign-up.


问:
Include GPLv2 licensed data in MIT licensed project
I'd like to include some data from a GPLv2 licensed project in my MIT licensed project.

More specifically, I want to use the data from the other project as the training data for my machine learning algorithm and I'd also like to include the trained model in my project.

I don't want to include the whole project source code, just those data files. I will not modify them. I also want to have the trained model in my project which I think is derived work?

Can I create a folder for those data files, add a copy of the GPLv2 license, make it clear that my project is MIT licensed apart from that folder which contains GPLv2 licensed files?

Does the trained model also have to be released under GPLv2? If so, can I also keep it in that folder?

答:
As I understand you are not going to redestribute that part that you borrowed from GPLv2 project. You just need carefully maintain dependency on that project - it's perfectly fine to use some GPL data during development as soon as your final product that you will release doesn't contain it.

From GPLv2:

This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope.


答: There is no need to reinvent the wheel - use the functionality of your favorite unit testing framework. For example, Nunit provides a "combinatorial" attribute (and some other helpful attributes like "sequential") which does exactly what you are looking for. For JUnit, you find add-ons like "jcombinatorial". I guess there are similar functionalities for other xUnit frameworks.</p>

Title: Testing all combinations


问:
Etiquette using code found on GitHub and using Code beyond included Libraries
I've been trying to find what I'm supposed to do when I want to use code I find on GitHub. I think this post had some good information but I'm still somewhat confused.

I want to use code found in this repository https://github.com/wcdolphin/python-bcrypt

So according to the answer given the post, I'm to take the content in the LICENSE file of that repository and add it to the LICENSE in my project? I understand that I should give acknowledgement to the creator, how do I do that? Do I create a .txt file in the directory that holds the module that is their code and say something like "Created by wcdolphin, found at https://github.com/wcdolphin/python-bcrypt"?

Also, I haven't used used libraries beyond what is included with the Python library before. I see installation instructions there, but that would only work on my machine right? Can I download and add these files into my project directory and use them as modules? I found this post but I'm not sure if I can custom install stuff on Google App Engine. I intend on hosting my project up there(I'm not going to try to homebrew encrypt super sensitive information, it's more of a demonstration) and I think, with my limited knowledge, uploading the source with my source would be the best way.

Thanks

答: If it is only demonstration I would not care that much. I think it is "fair use" (learning) more on wikipedia. Attribution is nice thing and thing to do. When your demonstration will turn into something bigger then you would have to get law advisor to cover your back. Not to rely on internet forums to get legal advice.</p>


答:
As I understand it, the GPL files serve as input to your software. In that case, your software can not be considered to be derived from the GPL files and is thus not affected by the copyleft nature of the GPL license.

The output of your program (when taking those GPL files as input) is derived from the GPL files and thus also bound by the GPL license.

This is under the assumption that the model for your algorithm will only be loaded into the algorithm at runtime and thus can be treated as data (for example, you can provide the algorithm with a different model without needing access to the source code). If this assumption is incorrect and the file containing the model is an integral part of your algorithm, then the GPL requires that you make the entire project available under that license.

As for distribution, you get the clearest situation if you split the distribution into two parts: one part with the MIT-licensed project and a second part with the GPL-licensed data and derived model. Then you can distribute both parts each with their appropriate license without possibly incurring confusion which parts are under which license.

Title: Include GPLv2 licensed data in MIT licensed project

Body:
I'd like to include some data from a GPLv2 licensed project in my MIT licensed project.

More specifically, I want to use the data from the other project as the training data for my machine learning algorithm and I'd also like to include the trained model in my project.

I don't want to include the whole project source code, just those data files. I will not modify them. I also want to have the trained model in my project which I think is derived work?

Can I create a folder for those data files, add a copy of the GPLv2 license, make it clear that my project is MIT licensed apart from that folder which contains GPLv2 licensed files?

Does the trained model also have to be released under GPLv2? If so, can I also keep it in that folder?


问:
Documenting higher-level concepts
I will be leaving my current project in a few days, and as part of securing my knowledge I have been asked to add comments to the code wherever I feel that can add value.

The problem I am running into now is that the comments I want to write are not really suitable as comments, because they do not pertain to a single entity in the code (a few lines, a function, a class or even a file), but they are more about how two or more entities interact with each other or about a feature whose implementation is spread over multiple entities.

So, how do you go about documenting the stuff that does not belong to a single entity but is important to know to understand the bigger picture?

And also: Where do you document it? In the source file or in an external document?

As an example, we have a client-server architecture in C (with the client and server both running on the same embedded device). To avoid flooding the server, the client has a mechanism to throttle the sending of similar requests to the server such that a request can only be sent if the previous one has been answered.

The innards of this mechanism are spread over multiple functions.

Where would you place the documentation of such a feature, especially if the file with the functionality also has some other, unrelated, functions?

Edit: Extended the question a bit.

答:
I suggest to keep the code intact and describe your design in MS Word with referenes to source code and supporting UML diagrams. Don't spend you efforts on wiki - you don't have neither time nor incentive for real cross referenced documentation. The real power of wiki is semantic network built around some topic and writing wiki with one page is poor style.

Any documentation that is written after project is finished tends to be official statement rather than guidence for supporter/maintainer. This is similar to writing unit tests after the module is implemented. Although they are still useful but they are much less detailed then if you write tests first.

Design decisions have to be pronounced before you started implementing something. It may be simple note like "Ok guys, I have an idea, what do you think about it?" or formal proposal with UML diagrams and meetings. Whenever I start new task/component I try to announce what exactly I'm going to do. And the medium that I choose is not really important - it can be email, blog, wiki, JIRA... Of course design will change in later development but these documents will serve as draft for release documentation.

Title: Documenting higher-level concepts


答: I think including python-bcrypt's license text as it is and adding yours above it should be ok. Since that's what the BSD license requires you to do. Just like what the author did when he included blowfish and bcrypt in his project.</p>

Title: Etiquette using code found on GitHub and using Code beyond included Libraries

Body:
I've been trying to find what I'm supposed to do when I want to use code I find on GitHub. I think this post had some good information but I'm still somewhat confused.

I want to use code found in this repository https://github.com/wcdolphin/python-bcrypt

So according to the answer given the post, I'm to take the content in the LICENSE file of that repository and add it to the LICENSE in my project? I understand that I should give acknowledgement to the creator, how do I do that? Do I create a .txt file in the directory that holds the module that is their code and say something like "Created by wcdolphin, found at https://github.com/wcdolphin/python-bcrypt"?

Also, I haven't used used libraries beyond what is included with the Python library before. I see installation instructions there, but that would only work on my machine right? Can I download and add these files into my project directory and use them as modules? I found this post but I'm not sure if I can custom install stuff on Google App Engine. I intend on hosting my project up there(I'm not going to try to homebrew encrypt super sensitive information, it's more of a demonstration) and I think, with my limited knowledge, uploading the source with my source would be the best way.

Thanks


问:
How do you respond to "Tell me a little bit about yourself." question in interviews?
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

答:
It isn't a silly question. I've been on both sides of the interview table and I think it is just another way of saying "Give me an executive summary of your resume and work experience."

You shouldn't dread this question. It is so open-ended that you can use it as a launching off point to direct the conversation directly to your strengths and give your pre-prepared elevator speech. You did prepare one, right? =)


问:
Some team members don't actively participate in Sprint planning
Some team members just wait until the stories they are most likely to work on will be discussed and only then they participate. Otherwise they just play with their phone and don't listen.

In some way I understand this position. Why listen to a discussion about a feature you are unlikely to help develop in the Sprint or ever?

What do you think we should do?

答:
What is your sprint duration?

Longer sprint durations lead to

More work to plan in the sprint, which leads to

Longer planning meetings, which leads to

Higher difficulty for team members to stay focused, ...

Team members get bored

So if if your sprint duration is more than two weeks, try working in shorter sprints.

If it is difficult to get the stakeholders to commit to shorter sprints, then you could skip some of the formal meetings, e.g. only have the sprint review after every 2 sprints, instead of after every sprint.


答:
This is probably something that people have needed to solve before.

Yes, indeed.

How do I solve this elegantly?

I would use Prolog, because it fits perfectly in this case.
Prolog predicates are made of different clauses; let's define
the x/1 predicate (x/1 means functor x with arity 1, a.k.a. the number of arguments) :

```<code>x(-1).
x(0).
x(1).
</code>```

We defined 3 alternative clauses for x/1 (order of declaration matters).
Then, any call to x(V) with V a free variable will leave "choice points" that are visited upon backtrack. Interactively:

```<code>[eclipse]: x(V).

V = -1
Yes (0.00s cpu, solution 1, maybe more) ? ;

V = 0
Yes (0.00s cpu, solution 2, maybe more) ? ;

V = 1
Yes (0.00s cpu, solution 3)
</code>```

We do not necessarily need to have two clauses, though:

```<code>y(Y) :- Y = "hello"; Y = "goodbye".
</code>```

Here, the ; disjunction operator separates two alternative unifications of variable V with different strings*.
Let's define also a z/1 predicate, using the between/4 built-in auxiliary predicate :

```<code>z(Result) :- between(0,100,1,Result).
</code>```

Now, you will need to call a specific test function, which depends heavily on your exact requirements. But here is a sketch of how to call it:

```<code>run :-
     x(X),
     y(Y),
     z(Z),
     test(X,Y,Z),
     % failing here will backtrack over other values of X, Y, Z.
     fail.

% since the previous clause of the run predicate always fail, we
% add another one that will succeed. It will be tried after all values of
% X, Y and Z have been attempted. Since there is no need to have a body, we
% simply write "run."
run.
</code>```

The control flow of the program is lead by an implicit backtracking mechanism: basically, in order to see if run/0 succeeds, we try both clauses, one after the other.
In order for the the first clause to succeed, all the goals that are listed must succeed. Goals x(X), y(Y) and z(Z) bind one of the possible values to free variables X, Y and Z. When we reach the fail predicate, which always fails, we must try alternative valuations of the free variables; first, all values for Z are tested, then another for Y and again, all values of Z, until we try all combinations of X, Y and Z. In fact, the first clause of run/0 can never succeed (but we try anyway, and as a side-effect we call the test with all combination of values). Finally, we end-up trying the other clause of run/0, which trivially succeeds.

The test/3 predicate is where you should define your test. You might want to concatenate all your terms and call an external shell, for example:

```<code>test(X,Y,Z) :-
    join_string(["./test",X,Y,Z]," ",Cmd),
    sh(Cmd).
</code>```

Alernatively, you can talk to another process with sockets or through a stream. This particular example does not handle possible spaces in arguments, so take care.

@Iserni pointed out that you might want to avoid doing an exhaustive search. If you think you need to cut down your search tree according to additional constraints, then you can encode your constraints and cost functions as predicates: this is exactly the kind of problems people solve daily with Prolog.

It isn't python or any other popular scripting language, but I think it is worth trying. After all, if it fails, you can just got back trying another option :-)

(*) Even though the resulting code is short, it could be shorter using only the member/2 predicate for X and Y (member(X,[-1,0,1]), member(Y,["hello","goodbye"])).

Title: Testing all combinations

Body:
This is probably something that people have needed to solve before.

Yes, indeed.

How do I solve this elegantly?

I would use Prolog, because it fits perfectly in this case.
Prolog predicates are made of different clauses; let's define
the x/1 predicate (x/1 means functor x with arity 1, a.k.a. the number of arguments) :

x(-1).
x(0).
x(1).

We defined 3 alternative clauses for x/1 (order of declaration matters).
Then, any call to x(V) with V a free variable will leave "choice points" that are visited upon backtrack. Interactively:

[eclipse]: x(V).

V = -1
Yes (0.00s cpu, solution 1, maybe more) ? ;

V = 0
Yes (0.00s cpu, solution 2, maybe more) ? ;

V = 1
Yes (0.00s cpu, solution 3)

We do not necessarily need to have two clauses, though:

y(Y) :- Y = "hello"; Y = "goodbye".

Here, the ; disjunction operator separates two alternative unifications of variable V with different strings*.
Let's define also a z/1 predicate, using the between/4 built-in auxiliary predicate :

z(Result) :- between(0,100,1,Result).

Now, you will need to call a specific test function, which depends heavily on your exact requirements. But here is a sketch of how to call it:

run :-
     x(X),
     y(Y),
     z(Z),
     test(X,Y,Z),
     % failing here will backtrack over other values of X, Y, Z.
     fail.

% since the previous clause of the run predicate always fail, we
% add another one that will succeed. It will be tried after all values of
% X, Y and Z have been attempted. Since there is no need to have a body, we
% simply write "run."
run.

The control flow of the program is lead by an implicit backtracking mechanism: basically, in order to see if run/0 succeeds, we try both clauses, one after the other.
In order for the the first clause to succeed, all the goals that are listed must succeed. Goals x(X), y(Y) and z(Z) bind one of the possible values to free variables X, Y and Z. When we reach the fail predicate, which always fails, we must try alternative valuations of the free variables; first, all values for Z are tested, then another for Y and again, all values of Z, until we try all combinations of X, Y and Z. In fact, the first clause of run/0 can never succeed (but we try anyway, and as a side-effect we call the test with all combination of values). Finally, we end-up trying the other clause of run/0, which trivially succeeds.

The test/3 predicate is where you should define your test. You might want to concatenate all your terms and call an external shell, for example:

test(X,Y,Z) :-
    join_string(["./test",X,Y,Z]," ",Cmd),
    sh(Cmd).

Alernatively, you can talk to another process with sockets or through a stream. This particular example does not handle possible spaces in arguments, so take care.

@Iserni pointed out that you might want to avoid doing an exhaustive search. If you think you need to cut down your search tree according to additional constraints, then you can encode your constraints and cost functions as predicates: this is exactly the kind of problems people solve daily with Prolog.

It isn't python or any other popular scripting language, but I think it is worth trying. After all, if it fails, you can just got back trying another option :-)

(*) Even though the resulting code is short, it could be shorter using only the member/2 predicate for X and Y (member(X,[-1,0,1]), member(Y,["hello","goodbye"])).


答:
Sounds like a motivational problem - why don't some people care about the project they're working on? Maybe its because the team is split into the 'organisers' and the 'left outs'.

So involve everyone, instead of 1 or 2 people taking charge of the planning sessions, you engage everyone - make different people take charge of each session, preferably make different people take charge during the session. Rotate it all around. I know this can seem difficult because there's always someone who wants to fuss about and organise everybody but they are the problem here.

Here's an idea: when planning choose a person at random to take charge of each story. At random. Record who was responsible for the planning of it too, so next sprint you can tell if they did a good job of getting a good consensus of estimates and task split. That'll make them pay attention, and will also give them a reason to engage with the project.

Remember, the problem isn't them, its you and the way your planning sessions are done. So when someone else takes over a story plan, they get to chose how to go about it there should be official way of proceeding. (ie don't sit back and continue to force your organisation upon them by proxy)

Title: Some team members don't actively participate in Sprint planning

Body:
Some team members just wait until the stories they are most likely to work on will be discussed and only then they participate. Otherwise they just play with their phone and don't listen.

In some way I understand this position. Why listen to a discussion about a feature you are unlikely to help develop in the Sprint or ever?

What do you think we should do?


答:
Duplication itself is not a problem - it's a way to get quick result. You just need to remember that you have technological debt and allocate time to generalize your code in the future.

What do you mean by going forwards is painful - are you planning something big or it's just additional features? There is only one reason for rewriting everything - the case when architecture of your current applicaiton doesn't fit your future development.

Once I had a project that I was developing for several months and it wasn't in particular 'dirty'. I also did unit testing. And then requirement changed and it took me two more months to understand that I have to change architecture. After I realised it I spend 3 weeks to completely rewrite that service - it was active development but I knew what to do.

I think your case is different - you just need to spend more time on cleaning. Start from small things. During next bugfix or implementation of a new feature don't jump right into development. Spend some time on cleaning. Take a rule to slightly improve any code that you touch. Of course without unit tests it's risky - and you will understand it very quickly so next time you will have more insentive to write unit tests.

At the same time you need to start thinking about high level design so you can start generalizing and decomposing system. Strictly speaking this is not refactoring. People tend to misuse this term.


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答:
If you walk up to a human on the street and ask "How big was a T-rex?" the answers would fluctuate even though majority of humans know what a T-rex is, how big it kind of was, but nobody really knows for certain - because we have NO relative scale to baseline from.

That's the cognitive behavior you're trying to figure out with forecasting and many methodologies spin cycles with "I've got it!..i have the secret to accurate forecasting!" snake oil to the masses. When you actually do forecast you're actually saying outloud "I will ALLOW x days/hours/points for that to complete" - its in a sense creating a "timebox" for that event to be carried out within.

For me, Points is just shifting the boundaries, at the end of the day unless you're in a team that is happy to say "*Well we have 3 weeks per sprint, and thumb suck...i figure we should shoot for 30 points to complete in that cycle! who's with me!*" and thats as deep as you go in forecast modeling - fine! ..as realistically you're just setting an arbitary budget and that's it. You're also then in retrospective looking at the work completed with a sense of "holy crap, we did 33pts that sprint, that was pretty cool" and not much can be done about that. You can use velocity to determine mid-sprint you're getting bang for your budget buck by asking outloud "Have we hit 15pts yet? will we" but then your back to adding relative time to the equation aren't you?"  but the danger here is you're now using Velocity to measure productivity not capacity which from what I understand kicks the Reactive Release Management (story points) in the head..

The point system is almost too clever to not notice that you still attach relative time to the equation, everything from your agreed "sprint cycles" to your daily standups in which you enact some hidden rule around duration + complexity = "Max is taking to long with that task" innate gut feeling team code red moment?

The human brain cant forecast because it involves a lot of working memory mixed with long/short term recall, so its like asking a novice math student to do fractions in their head not on paper.. It's why other industries never agree on a forecast and constantly validate forecasts in relative time (eg geologist never stop forecast modelling until that cubic meter has been dug out of the ground and then its "done").

I'd say Point system works if you're not forecasting. You're agreeing to a chunk of work that's based on a sub-chunking algorithm but that's really your closest approach to forecasting as possible. In fact you're release management would look for natural breaks in the "backlog" queue that fit around theme(s) (ie in Silverlight we Product managers would wait until after they complete their backlog and piece together the themes we initially set. We never knew what the engineering team were doing specifically we just had a basic outline. We'd then take that body of work and build our marketing event around it (Microsoft Mix))

When you start locking down velocity expectations inside sprint cycles that rely on velocity + time, you're back to forecasting estimations again only this time you're worse off because you're playing the "it depends game" ... More importantly you're also killing potential for team growth / career growth as well.

The tax you pay for Points vs Time is with points you need to look for alternative measurement formulas to track onjob skill development / mentoring or developer behavior.

As in you will still need look at a "median developer" as your ideal person to attach skill/effort with, you can then baseline other developers with that person to determine how they are fairing in their ongoing growth within your team. It also highlights situations where the "fast" developers are carrying most of the water but are getting bored or worse they are working longer hours and no recognition / reward because of competing deadlines etc. Standups don't unearth this in reality, they are really there to detect bad smells within the team per say, as in "that person is struggling, lets help"

Next also comes the "carry over" stories, stories that don't get chunked into that sprint cycle but then spill over to the next sprint cycle. Which then can easily create a knock-on effect if you're factoring in time, but the moment you do factor in relative time..again, you just regressed back to "time based forecasting/estimation" and again the point system is just muddying the waters.

If you go points you have ignore time completely and i mean completely as the moment you let time creep in you're gaming the idea / methodology.

Having travelled around the world as an Evangelist, I saw a lot of teams swear their hand on whatever they hold dear that they have cracked the Agile Forecast code... but I always clicked my tongue, smiled and walked away with the thought "yeah...you almost did, but that mistress we call 'time'... she's just cruel..."


答:
In order to come up with a better name, you have to take the time to understand what the classes and methods do. You'd think during a code review, they would be able to figure it out, but apparently they look at the names and stop right there. They can't tell you what is missing or more accurate.

Seems like your only response is, "This class is Foo because it is a foo which is a _ . What else could I call it?" If they can't give you an answer, you'll just have to leave it.


问:
Does limiting commitment in Scrum lead to complacency?
In my organization Scrum teams almost never finish all of their stories 100%. I suggested that we commit to fewer stories each Sprint, but the R&D manager says if we do that people will still not complete the work, but will just do less of it thus slowing down development. He says there is a Student Syndrome at work here.

What is your take on that?

答:
Who cares? Shouldn't the produce owner be asking where's the rest of my features?

You may need to limit the length of your sprints. This way more progress has to be shown along with way. Use the feedback on what is getting done to determine how much can be accomplished in subsequent sprints.

You can't have a fixed timeframe for a project and a fixed list of stores/features without allocating enough resources. If there is a fixed due date, you may not get all the stories finished. You want to cut out some stories?  Which ones? Can you really determine that at the beginning? Hopefully, if you prioritize right, the product owner gets what's most important. It's their priority after-all.

The manager is playing mind games. If you're a kid who wants a dog, ask for a pony.