问:
Java regex patterns - compile time constants or instance members?
Currently, I have a couple of singleton objects where I'm doing matching on regular expressions, and my Patterns are defined like so:

```<code>class Foobar {
  private final Pattern firstPattern =
    Pattern.compile("some regex");
  private final Pattern secondPattern =
    Pattern.compile("some other regex");
  // more Patterns, etc.
  private Foobar() {}
  public static Foobar create() { /* singleton stuff */ }
}
</code>```

But I was told by someone the other day that this is bad style, and Patterns should always be defined at the class level, and look something like this instead:

```<code>class Foobar {
  private static final Pattern FIRST_PATTERN =
    Pattern.compile("some regex");
  private static final Pattern SECOND_PATTERN =
    Pattern.compile("some other regex");
  // more Patterns, etc.
  private Foobar() {}
  public static Foobar create() { /* singleton stuff */ }
}
</code>```

The lifetime of this particular object isn't that long, and my main reason for using the first approach is because it doesn't make sense to me to hold on to the Patterns once the object gets GC'd.

Any suggestions / thoughts?

答:
Java Pattern objects are thread safe and immutable (its the matchers that are not thread safe).

As such, there is no reason not to make them static if they are going to be used by each instance of the class (or again in another method in the class).

Making them instance variables, no matter how short (or long) their life time means that you are recompiling the regular expression each time you create an instance of a class.

One of the key reasons for this structure (Pattern being a factory for Matcher objects) is that compiling the regular expression into its finite automata is a moderately expensive action.  However, one finds that often the same regular expression is used again and again in a given class (either through multiple invocations of the same method or different spots in the class).

The Matcher, on the other hand is rather light - it points to the state of the pattern within the Pattern and the location within the character array for the string.

For a singleton, it shouldn't matter too much, because after all, there's only one instance of it that sits around and you aren't recreating the singleton again and again (wait, 'lifetime of the singleton isn't that long'? Does this mean you are instantiating it multiple times over the course of the application?)

However, you will find that some static source code analyzers don't recognize that something is a singleton and will complain that you are creating instances of patterns from constants for each instance of the class.

The problem with all of this is that it is a not good (its not bad for a singleton either) choice and you may start ignoring other warnings for things that the compiler and analysis tools tell you about (read more about broken windows).

Related:

Shouldn't “static” patterns always be static?

Is Java Regex Thread Safe?

java.util.regex - importance of Pattern.compile()?


问:
Finding the order of a set's elements
A little rephrased, in the form of a game, real-life problem:

Suppose there is a set of elements {1, 2, ..., n}. Player A has chosen a single permutation of this set. Player B wants to find out the order of the elements by asking questions of form "Is X earlier in the permutation than Y?", where X and Y are elements of the set.

Assuming B wants to minimize the amount of questions, how many times would he have to ask, and what would be the algorithm?

答:
This is exactly similar to a comparison based sorting problem. That is, we have all the elements in a scrambled order and wants to sort them using only comparisons (e.g. is X < Y)

As such, any comparison based sort algorithm will work. The performance of these varies, but we know for sure that we cannot get a running time below O(n*log(n)) for comparison based sorting. In many actual sorting scenarios, we can actually do better - but in this case we can only rely on comparisons, hence this is a hard limit on the running time.

Several algorithms exists for this problem:

```<code>                  Best case      Avg. case      Worst case     Worst case memory usage
Quicksort         O(n log(n))    O(n log(n))    O(n^2)         O(n)
Mergesort         O(n log(n))    O(n log(n))    O(n log(n))    O(n)
Heapsort          O(n log(n))    O(n log(n))    O(n log(n))    O(1)
Bubble Sort       O(n)           O(n^2)         O(n^2)         O(1)
Insertion Sort    O(n)           O(n^2)         O(n^2)         O(1)
Selection Sort    O(n^2)         O(n^2)         O(n^2)         O(1)
</code>```

Apart from running time and memory usage, it should be mentioned that Insertion Sort is fastest for small arrays (optimized versions of mergesort might switch to Insertion Sort when arrays get small). Selection sort uses the smallest amount of actual swaps - which might be fast on systems where such swaps are expensive.

Some of the algorithms are unstable, meaning that equal elements are not guaranteed to come out in the order that we fetch them - however, this should not make any difference in this case, as there is no initial order in a set.

Finally, note that Quicksort has a worse worst case running time than Mergesort and Heapsort. However, for most inputs Quicksort often proves to be as fast or faster than these, due to the way you can actually implement the algorithm.

ContentLicense: CC BY-SA 3.0

Title: Finding the order of a set's elements

Body:
This is exactly similar to a comparison based sorting problem. That is, we have all the elements in a scrambled order and wants to sort them using only comparisons (e.g. is X < Y)

As such, any comparison based sort algorithm will work. The performance of these varies, but we know for sure that we cannot get a running time below O(n*log(n)) for comparison based sorting. In many actual sorting scenarios, we can actually do better - but in this case we can only rely on comparisons, hence this is a hard limit on the running time.

Several algorithms exists for this problem:

                  Best case      Avg. case      Worst case     Worst case memory usage
Quicksort         O(n log(n))    O(n log(n))    O(n^2)         O(n)
Mergesort         O(n log(n))    O(n log(n))    O(n log(n))    O(n)
Heapsort          O(n log(n))    O(n log(n))    O(n log(n))    O(1)
Bubble Sort       O(n)           O(n^2)         O(n^2)         O(1)
Insertion Sort    O(n)           O(n^2)         O(n^2)         O(1)
Selection Sort    O(n^2)         O(n^2)         O(n^2)         O(1)

Apart from running time and memory usage, it should be mentioned that Insertion Sort is fastest for small arrays (optimized versions of mergesort might switch to Insertion Sort when arrays get small). Selection sort uses the smallest amount of actual swaps - which might be fast on systems where such swaps are expensive.

Some of the algorithms are unstable, meaning that equal elements are not guaranteed to come out in the order that we fetch them - however, this should not make any difference in this case, as there is no initial order in a set.

Finally, note that Quicksort has a worse worst case running time than Mergesort and Heapsort. However, for most inputs Quicksort often proves to be as fast or faster than these, due to the way you can actually implement the algorithm.


问:
Should my colleagues review each others code from source control system?
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.

答:
If said colleague provides good and constructive feedback, this is a fantastic thing and you should appreciate it very much.

This WILL catch bugs you didn't think of when writing it.  This WILL result in you writing better code because you know that others will see it.

ContentLicense: CC BY-SA 2.5


问:
IL and case-sensitivity
Quoted from A Brief Introduction To IL code, CLR, CTS, CLS and JIT In .NET

CLS stands for Common Language Specifications. It is a subset of CTS.
  CLS is a set of rules or guidelines which if followed ensures that
  code written in one .NET language can be used by another .NET
  language. For example one rule is that we cannot have member functions
  with same name with case difference only i.e we should not have add()
  and Add(). This may work in C# because it is case-sensitive but if try
  to use that C# code in VB.NET, it is not possible because VB.NET is
  not case-sensitive.

Based on above text I want to confirm two points here:

Does the case-sensitivity of IL is a condition for member functions only, and not for member properties?

Is it true that C# wouldn't be inter-operable with VB.NET if it didn't take care of the case sensitivity?

答:
Does the case-sensitivity of IL is a condition for member functions only, and not for member properties?

C# properties are implemented internally as special methods called accessors so the above quote applies to both methods and properties.

Is it true that C# wouldn't be inter-operable with VB.NET if it didn't take care of the case sensitivity?

Theoretically, it may be possible to write C# that is compatible with VB.NET. However, it is not just case sensitivity. For example, the many keywords appear in one language and not the other need special syntax (which C# and VB.NET both provide). Unsigned types cannot be exposed and operators cannot be overloaded. For more details, see https://stackoverflow.com/questions/570452/what-is-the-clscompliant-attribute-in-net.

Rather than manually having to check these, Microsoft created CLS as a way of programmaticly enforcing it. More importantly, it also allows languages other than VB.NET and C# to interoperate through a common runtime, including hose that lack a special syntax for invalid identifiers.

Title: IL and case-sensitivity


问:
Is it reasonable to null guard every single dereferenced pointer?
At a new job, I've been getting flagged in code reviews for code like this:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender) { }

void PowerManager::SignalShutdown()
{
    msgSender_->sendMsg("shutdown()");
}
</code>```

I'm told that last method should read:

```<code>void PowerManager::SignalShutdown()
{
    if (msgSender_) {
        msgSender_->sendMsg("shutdown()");
    }
}
</code>```

i.e., I must put a NULL guard around the msgSender_ variable, even though it is a private data member. It's difficult for me to restrain myself from using expletives to describe how I feel about this piece of 'wisdom'. When I ask for an explanation, I get a litany of horror stories about how some junior programmer, some-year, got confused about how a class was supposed to work and accidentally deleted a member he shouldn't have (and set it to NULL afterwards, apparently), and things blew up in the field right after a product release, and we've "learned the hard way, trust us" that it's better to just NULL check everything.

To me, this feels like cargo cult programming, plain and simple. A few well-meaning colleagues are earnestly trying to help me 'get it' and see how this will help me write more robust code, but... I can't help feeling like they're the ones who don't get it.

Is it reasonable for a coding standard to require that every single pointer dereferenced in a function be checked for NULL first—even private data members? (Note: To give some context, we make a consumer electronics device, not an air traffic control system or some other 'failure-equals-people-die' product.)

EDIT: In the above example, the msgSender_ collaborator isn't optional. If it's ever NULL, it indicates a bug. The only reason it is passed into the constructor is so PowerManager can be tested with a mock IMsgSender subclass.

SUMMARY: There were some really great answers to this question, thanks everyone. I accepted the one from @aaronps chiefly due to its brevity. There seems to be fairly broad general agreement that:

Mandating NULL guards for every single dereferenced pointer is overkill, but

You can side-step the whole debate by using a reference instead (if possible) or a const pointer, and

assert statements are a more enlightened alternative to NULL guards for verifying that a function's preconditions are met.

答:
This example seems to be more about object lifetime than whether or not an input parameter is null†. Since you mention that the PowerManager must always have a valid IMsgSender, passing the argument by pointer (thereby allowing the possibility of a null pointer) strikes me as a design flaw††.

In situations like this, I would prefer to change the interface so the caller's requirements are enforced by the language:

```<code>PowerManager::PowerManager(const IMsgSender& msgSender)
  : msgSender_(msgSender) {}

void PowerManager::SignalShutdown() {
    msgSender_->sendMsg("shutdown()");
}
</code>```

Rewriting it this way says that PowerManager needs to hold a reference to IMsgSender for it's entire lifetime. This, in turn, also establishes an implied requirement that IMsgSender must live longer than PowerManager, and negates the need for any null pointer checking or assertions inside PowerManager.

You can also write the same thing using a smart pointer (via boost or c++11), to explicitly force IMsgSender to live longer than PowerManager:

```<code>PowerManager::PowerManager(std::shared_ptr<IMsgSender> msgSender)
  : msgSender_(msgSender) {}

void PowerManager::SignalShutdown() {
    // Here, we own a smart pointer to IMsgSender, so even if the caller
    // destroys the original pointer, we still have a valid copy
    msgSender_->sendMsg("shutdown()");
}
</code>```

This method is prefered if it is possible that IMsgSender's lifetime can not be guaranteed to be longer than PowerManager's (i.e., x = new IMsgSender(); p = new PowerManager(*x);).

† With regard to pointers: rampant null checking makes code harder to read, and does not improve stability (it improves the appearance of stability, which is much worse).

Somewhere, someone got an address for memory to hold the IMsgSender. It is that function's responsibility to make sure that the allocation succeeded (checking library return values or properly handling std::bad_alloc exceptions), so as to not pass around invalid pointers.

Since the PowerManager does not own the IMsgSender (it's just borrowing it for a while), it is not responsible for allocating or destroying that memory. This is another reason why I prefer the reference.

†† Since you're new at this job, I expect that you're hacking on existing code. So by design flaw, I mean that the flaw is in the code that you're working with. Thus, the people who are flagging your code because it's not checking for null pointers are really flagging themselves for writing code that requires pointers :)

Body:
This example seems to be more about object lifetime than whether or not an input parameter is null†. Since you mention that the PowerManager must always have a valid IMsgSender, passing the argument by pointer (thereby allowing the possibility of a null pointer) strikes me as a design flaw††.

In situations like this, I would prefer to change the interface so the caller's requirements are enforced by the language:

PowerManager::PowerManager(const IMsgSender& msgSender)
  : msgSender_(msgSender) {}

void PowerManager::SignalShutdown() {
    msgSender_->sendMsg("shutdown()");
}

Rewriting it this way says that PowerManager needs to hold a reference to IMsgSender for it's entire lifetime. This, in turn, also establishes an implied requirement that IMsgSender must live longer than PowerManager, and negates the need for any null pointer checking or assertions inside PowerManager.

You can also write the same thing using a smart pointer (via boost or c++11), to explicitly force IMsgSender to live longer than PowerManager:

PowerManager::PowerManager(std::shared_ptr<IMsgSender> msgSender)
  : msgSender_(msgSender) {}

void PowerManager::SignalShutdown() {
    // Here, we own a smart pointer to IMsgSender, so even if the caller
    // destroys the original pointer, we still have a valid copy
    msgSender_->sendMsg("shutdown()");
}

This method is prefered if it is possible that IMsgSender's lifetime can not be guaranteed to be longer than PowerManager's (i.e., x = new IMsgSender(); p = new PowerManager(*x);).

† With regard to pointers: rampant null checking makes code harder to read, and does not improve stability (it improves the appearance of stability, which is much worse).

Somewhere, someone got an address for memory to hold the IMsgSender. It is that function's responsibility to make sure that the allocation succeeded (checking library return values or properly handling std::bad_alloc exceptions), so as to not pass around invalid pointers.

Since the PowerManager does not own the IMsgSender (it's just borrowing it for a while), it is not responsible for allocating or destroying that memory. This is another reason why I prefer the reference.

†† Since you're new at this job, I expect that you're hacking on existing code. So by design flaw, I mean that the flaw is in the code that you're working with. Thus, the people who are flagging your code because it's not checking for null pointers are really flagging themselves for writing code that requires pointers :)


问:
How can a collection class instantiate many objects with one database call?
I have a baseClass where I do not want public setters. I have a load($id) method that will retrieve the data for that object from the db.

I have been using static class methods like getBy($property,$values) to return multiple class objects using a single database call. But some people say that static methods are not OOP.

So now I'm trying to create a baseClassCollection that can do the same thing. But it can't, because it cannot access protected setters. I don't want everyone to be able to set the object's data. But it seems that it is an all-or-nothing proposition. I cannot give just the collection class access to the setters.

I've seen a solution using debug_backtrace() but that seems inelegant. I'm moving toward just making the setters public.

Are there any other solutions? Or should I even be looking for other solutions?

答:
Static methods aren't automatically non-OOP.  If they improve encapsulation or reuse value, they're probably fine.  In general, the interface to a class includes all the routines that work together to carry out that class's work, even if they are static or non-member.  Scott Myers wrote a DDJ article on non-members, for example.

Different languages have different levels of support for access restrictions.  In C++, you could use the named constructor idiom, but make the static construction members (e.g., static baseClass newClass(...)) private.  Then no one can create instances of baseClass.  Then make the baseClassCollection a friend of baseClass and baseClassCollection will be able to create baseClass instances from the database using the named constructor.


问:
What are common patterns for handling possible pluralization in message properties?
Obviously users like to see text properly pluralized, and pluralization schemes vary in the various written languages one may encounter.  When internationalizing an app, what pattern(s) are useful for handling messages with possible pluralization?  What about messages with multiple possible pluralization?

For example: "N review(s):"

One pattern would be

```<code>reviews.title.singular="{0} review:"
reviews.title.plural="{0} reviews:"
</code>```

And this may not support all languages.

Or a more complicated case: "Found M question(s) with N comment(s)."

This would be difficult to support even in English.

答:
the pattern I have seen used is to create a specific pattern for it with describes the ranges of each value

for example in java it is

```<code>"Found {0,choice,0#no questions|1#a single question|1<{0,number,integer} questions} with "+
"{1,choice,0#no comments|1#a single comment|1<{1,number,integer} comments}."
</code>```

it is a pain for something like that but fully translatable to languages with odd rules

Body:
the pattern I have seen used is to create a specific pattern for it with describes the ranges of each value

for example in java it is

"Found {0,choice,0#no questions|1#a single question|1<{0,number,integer} questions} with "+
"{1,choice,0#no comments|1#a single comment|1<{1,number,integer} comments}."

it is a pain for something like that but fully translatable to languages with odd rules


问:
How can I unit test that a class uses a trait in the expected manner?
A class has a trait.

The class is expected to call a function provided by the trait during a certain method invocation.

How do I write a unit test to ensure that that happens?

The difficulty, to me, comes from the fact that a trait is part of the class definition, so I cannot mock the trait in the test, as I could if the trait was instead an object that was passed in to the class constructor.

答:
What does the trait do? If the trait changes state, then check that the state was properly changed. If the trait fetches some data, make sure it is fetched and processed correctly.

Your unit is the method itself, not the trait it depends on. Treat the trait as an implementation detail of the method, since that's what it is.


问:
How to improve skills in software architecture
What is the best way to improve your skills in software architecture? We were taught design patterns in university, and I see plenty of books with simple and straight forward examples, but aside from them, how can you learn good architecture? In other words, how does one evolve into a great architect? What are the prerequisites?</p>

答:
A coder thinks about solving the problem; an architect thinks about maintaining the solution, limits the implementation imposes on the solution, areas of the implementation to improve as time permits, areas of the implementation that can be left out or reduced in scope if the schedule slips, dependencies (both internal and external) that can impact the performance of the implementation and things that can be done to limit the risk exposure, the training required for new users of the system, the documentation being developed and changes needed as the implementation deviates from the envisioned solution, and how the stake holders feel about the progress that is being made and the applicability of the implementation to the actual problem being solved.

Being an architect requires you to be able to communicate effectively, organize your thoughts and plans into a workable schedule, decompose a problem into implementable pieces, build prototypes of technically challenging pieces, and coordinate the implementation of the pieces so that everything finishes on time.

Learn to diagram your solution using Enterprise Architect, Visio, or pencil and paper.  As mentioned in other answers, get an architect mentor and share your solution diagrams with them for review.  Listen to the feedback and revise your diagrams.

Learn to build realistic schedules.  Start tracking how long it takes you to implement things, and keep track of how close you are to correctly estimating how long it takes.

Break down your next assignment into small pieces before you start coding and keep track of the steps you left out.  Learn to anticipate problem areas and prototype them before you start coding the final solution.

The article linked by Pierre 303 over in this answer to a similar question is worth adding here as well:

Who needs an architect from Martin Fowler

OwnerDisplayName: codetc


问:
How to slowly release a web application to more and more users so that too many concurrent users don't crash your site?
I have a web application that I expect to go viral pretty quickly.

How can I control traffic to it so that it doesn't crash under too much load?

This application doesn't require user login.
It will be properly load tested, but I am not really sure what kind of traffic to expect until I make it live.

答: Use a Load Balancer to direct traffic to two sites, one being the live site, the other being a welcome page with a friendly message asking the visitor to try again later...</p>


问:
Is a Mission Oriented Architecture (MOA) a better way to describe things than SOA?
I might sound like a troll, but I would like to seriously understand this deeper. The place I work at has started to use the term MOA, versus SOA as we believe it drives more clarity and want to compare it to the true goals of SOA.

A Mission Oriented Architecture is an approach whereby an application is broken down into various business mission elements, with the database, file assets, batch and real time functionality all tightly coupled in terms of delivering that piece of the functionality. The mission allows the developers to focus on a specific piece of functionality to get it right, and to build it with the ability for that piece to scale as an independent entity within the overall application. By tightly coupling the data, file assets and business logic you achieve the goals of working on a very large problem in bite size pieces.

Some definitions of SOA mix it up with what is essentially a method call on a web service versus a true "service". As an architect, I have always found it fun getting everyone on the same page regarding SOA.

Is it better to call it a "mission" versus a "service"?

答:
NO, I don't believe you should push to change the terminology from SOA to MOA.  Unless you believe you convince the entire world to update all references to SOA.

You are right, when you say that people working together must use terminology that is understood to mean the same thing for everyone. In your mind Mission Oriented Architecture sounds like a better choice, but when I read this question I thought you were talking about applications that launch rockets to the moon.  Clearly if I was to work with you, you still can't assume that I will have same interpretation of the term that you already have.

SOA isn't a term that your team or your company came up with. If you want someone to get educated (no matter how fun it it) in what SOA is, you can start by having them read external links:

http://en.wikipedia.org/wiki/Service-oriented_architecture

http://msdn.microsoft.com/en-us/library/bb833022.aspx

But when someone joins your team, or an third-party company integrates with you they are going to get this:

http://renewableplus.blogspot.com/2012/06/mission-oriented-architecture-moa.html  (it's a coincidence that there's actually a picture of a rocket on that page.  That was just one of top google hits that I found after I wrote the above stuff)


答: As a newbie to this site and the risk of not knowing proper etiquette, why don't you design the application with scale-out in mind, immediately.  Start with a scale-out NoSQL or similar database on the back end, caching layer below the site, distributed services that scale automatically (SOA, if you will) or as someone says at the press of button.  The window of opportunity is narrow on things, why not plan for fast expansion and catch the wave versus trying to control users.  There are software frameworks that you can build with right now, depending on what technologies you need, that have scale out in mind.</p>

Title: How to slowly release a web application to more and more users so that too many concurrent users don't crash your site?

Body:
I have a web application that I expect to go viral pretty quickly.

How can I control traffic to it so that it doesn't crash under too much load?

This application doesn't require user login.
It will be properly load tested, but I am not really sure what kind of traffic to expect until I make it live.


答:
Sounds like a bad idea to me.

The whole point of SOA is to design your architecture around simple, composable, loosely coupled services that can be used to achieve not just your current "mission" but also the future "missions" that may emerge (as they always do....).

If you tightly couple everything around a specific "mission", then you're just back in the bad old methodology of building a new, project-specific, maybe over-engineered, incompatible software stack for each application. And you'll probably soon find yourself creating a messy web of point-to-point integrations between them as new requirements emerge.

There's nothing wrong of course about having a "mission" in itself - in fact it's a very useful way to stay focused on what actually creates value. But you shouldn't fall into the trap of structuring your application architecture around it.

P.S. Don't confuse SOA with "web services". That's one way of implementing a remote service, but it's perfectly possible to do SOA without them. For example, you can implement a loosely coupled service pattern perfectly well with Java interfaces in a JVM process.

Title: Is a Mission Oriented Architecture (MOA) a better way to describe things than SOA?

Body:
I might sound like a troll, but I would like to seriously understand this deeper. The place I work at has started to use the term MOA, versus SOA as we believe it drives more clarity and want to compare it to the true goals of SOA.

A Mission Oriented Architecture is an approach whereby an application is broken down into various business mission elements, with the database, file assets, batch and real time functionality all tightly coupled in terms of delivering that piece of the functionality. The mission allows the developers to focus on a specific piece of functionality to get it right, and to build it with the ability for that piece to scale as an independent entity within the overall application. By tightly coupling the data, file assets and business logic you achieve the goals of working on a very large problem in bite size pieces.

Some definitions of SOA mix it up with what is essentially a method call on a web service versus a true "service". As an architect, I have always found it fun getting everyone on the same page regarding SOA.

Is it better to call it a "mission" versus a "service"?


问:
What can Go chan do that a list cannot?
I want to know in which situation Go chan makes code much simpler than using list or queue or array that is usually available in all languages.

As it was stated by Rob Pike in one of his speeches about Go lexer, Go channels help to organize data flow between structures that are not homomorphic.

I am interested in a simple Go code sample with chan that becomes MUCH more complicated in another language (for example C#) where chan is not available.

I am not interested in samples that use chan just to increase performance by avoiding waiting of data between generating list and consuming the list (which can be solved by chunking) or as a way to organize thread safe queue or thread-safe communication (which can be easily solved by locking primitives).

I am interested in a sample that makes code simpler structurally disregarding size of data.

If such sample does not exist then sample where size of data matters.

I guess desired sample would contain bi-directional communication between generator and consumer.

Also if someone could add tag [channel] to the list of available tags, that would be great.

答: Channels and lists used a queues are very similar. In go, channels are designed to work with goroutines. Goroutines allows your program to utilize all the core of your computer. Channels allow the goroutines to share data safely across cores. Channels also allows goroutines to synchronize with the data.</p>

Title: What can Go chan do that a list cannot?


问:
How to make code-review feel less like a way to *shift* the responsibility?
Sometimes it seems to me that people ask for code-reviews just so they would be able to say "Xyz reviewed my code!"(1) when something broke.

Question, is that ever the case? (Or is it just my imagination)
If it is, how do I handle this?

(1): What s/he really meant: It's Xyz's fault or something along those lines.

答:
If the first thing a developer thinks when their code fails is shifting the blame, it sounds like a broader cultural issue. Does the developer feel too attached to their code and so is their ego to blame? Is the developer inexperienced or feel they have something to prove?

Alternatively, does management yell at developers for defects and say nothing when things work? Is the team under pressure to shed headcount? Are developers uncomfortable with technologies and processes? When developers are told to fix an issue, do they feel they are blamed?

Everyone makes mistakes. The best software developers admit it, learn from it and move on. However, if a single mistake from a single person is enough to cause a large problem, this is a wider system problem and the responsibility of management.

Assuming none of these are the problem and returning to code reviews, code reviews are about a lot more than finding bugs. For example, it is knowledge sharing, ensuring code style is consistent, ensuring unit tests are done and documentation is up to date.

The best code reviews are two way discussions between the reviewers and authors and are soon reciprocated with the reviewers code. If the developers enjoy it and get value out of it, blame will not occur. The responsibility for quality code rests with the team and not Xyz.


问:
What is a Ruby on Rails way to save images?
I develop on iOS, and I'm switching from a PHP backend to Ruby on Rails. The interchange format is JSON.

A quick Google search for 'save images in Rails' has nearly every result talking about saving image data as blobs to the database. I might be mistaken, but I'm under the impression that saving image data in a database is a huge waste of time and space (as opposed to saving a link to the file location ('/img/subcat/4656.png').

In PHP, it's pretty standard to receive the data, generate a filename, save that file to disk, and update the database with the image's location on disk. Is this the same for Ruby on Rails, or is there some built-in ActiveRecord image functionality I'm not aware of?

答:
I've tried several gems, but now I'm using FineUploader together with PaperClip

FineUploader handles a lot of the GUI for you, for example upload progress, drag-and-drop and multiple file uploads, and so on. I'm using PaperClip because I want to store the images on my servers instead of on S3.

What we normally do is look for a stable out-of-the-box configurable solution instead of recreating stuff from scratch. With PaperClip I store the images and with a StateMachine I do conversions on the images and put them into a category based on filename. I had the same question you had, and this was my best working solution, that's why I share it.


答:
For our purposes, this is the same question as:

Assume I have two classes A and B:

```<code>abstract class A:
  method foo: 42;
  virtual method bar;

class B extends A:
  method bar: self.foo() + 4;
</code>```

How can I unit-test class B, considering that I cannot mock A?

If the language you are using is sufficiently dynamic, you could actually replace the A type with a mocked class. If the language treats types as first class objects, you could do a form of dependency injection. Otherwise, you could still use conditional compilation to switch between actual A for production and integration tests and a mock A' for unit testing – but that is prone to hide or even create bugs.

But quite frankly, this complexity seems silly to me. I'd rather write a suite of general unit tests for the supertype A, which get inherited for every type B that  somehow extends, does or implements A. Because A itself cannot be instantiated, it can be tested by a mock B'. After that, I'd test the other subtypes of A both with the A test suite, and their individual tests.

Yes, you can argue that this is a bit of an integration test rather than an unit test. However, it would be wise to treat the whole type with all inherited stuff and all traits composed into it as your unit, in contrast to just the parts you newly added in this class.

Title: How can I unit test that a class uses a trait in the expected manner?

Body:
A class has a trait.

The class is expected to call a function provided by the trait during a certain method invocation.

How do I write a unit test to ensure that that happens?

The difficulty, to me, comes from the fact that a trait is part of the class definition, so I cannot mock the trait in the test, as I could if the trait was instead an object that was passed in to the class constructor.

Body:
For our purposes, this is the same question as:

Assume I have two classes A and B:

abstract class A:
  method foo: 42;
  virtual method bar;

class B extends A:
  method bar: self.foo() + 4;

How can I unit-test class B, considering that I cannot mock A?

If the language you are using is sufficiently dynamic, you could actually replace the A type with a mocked class. If the language treats types as first class objects, you could do a form of dependency injection. Otherwise, you could still use conditional compilation to switch between actual A for production and integration tests and a mock A' for unit testing – but that is prone to hide or even create bugs.

But quite frankly, this complexity seems silly to me. I'd rather write a suite of general unit tests for the supertype A, which get inherited for every type B that  somehow extends, does or implements A. Because A itself cannot be instantiated, it can be tested by a mock B'. After that, I'd test the other subtypes of A both with the A test suite, and their individual tests.

Yes, you can argue that this is a bit of an integration test rather than an unit test. However, it would be wise to treat the whole type with all inherited stuff and all traits composed into it as your unit, in contrast to just the parts you newly added in this class.


答:
The restriction on case-sensitivity applies to all members (fields, methods, properties) visible to other assemblies. Thus, the following is OK:

```<code>[CLSCompliant(true)]
public class C
{
    private int i;
    public int I { get { return i; } set { i = value; } }
}
</code>```

but the following isn't:

```<code>[CLSCompliant(true)]
public class C
{
    public int i;
    public int I { get { return i; } set { i = value; } }
}
</code>```

and the following isn't either:

```<code>[CLSCompliant(true)]
public class C
{
    protected int i;
    public int I { get { return i; } set { i = value; } }
}
</code>```

since a VB.NET class might want to inherit from class C.

If the second example above were in a C# library and a VB.NET project would try to use it, the following code would not compile:

```<code>Dim c As New C()
Console.WriteLine(c.I)
</code>```

This is the compile-time error that the VB.NET compiler would throw:

'I' is ambiguous because multiple kinds of members with this name exist in class 'C'.

Title: IL and case-sensitivity

Body:
Quoted from A Brief Introduction To IL code, CLR, CTS, CLS and JIT In .NET

CLS stands for Common Language Specifications. It is a subset of CTS.
  CLS is a set of rules or guidelines which if followed ensures that
  code written in one .NET language can be used by another .NET
  language. For example one rule is that we cannot have member functions
  with same name with case difference only i.e we should not have add()
  and Add(). This may work in C# because it is case-sensitive but if try
  to use that C# code in VB.NET, it is not possible because VB.NET is
  not case-sensitive.

Based on above text I want to confirm two points here:

Does the case-sensitivity of IL is a condition for member functions only, and not for member properties?

Is it true that C# wouldn't be inter-operable with VB.NET if it didn't take care of the case sensitivity?

Body:
The restriction on case-sensitivity applies to all members (fields, methods, properties) visible to other assemblies. Thus, the following is OK:

[CLSCompliant(true)]
public class C
{
    private int i;
    public int I { get { return i; } set { i = value; } }
}

but the following isn't:

[CLSCompliant(true)]
public class C
{
    public int i;
    public int I { get { return i; } set { i = value; } }
}

and the following isn't either:

[CLSCompliant(true)]
public class C
{
    protected int i;
    public int I { get { return i; } set { i = value; } }
}

since a VB.NET class might want to inherit from class C.

If the second example above were in a C# library and a VB.NET project would try to use it, the following code would not compile:

Dim c As New C()
Console.WriteLine(c.I)

This is the compile-time error that the VB.NET compiler would throw:

'I' is ambiguous because multiple kinds of members with this name exist in class 'C'.


答:
Your Domain class (let's say a Book class) loads itself from the DB?
I'd rather avoid that, because this way you mix up the domain model with persistence code.

However, to your question: what I've seen in some frameworks in Java is that they define a public interface (in your case defining getters), and the implementation class has only, let's say, package accessibility. The receiver of the instance sees only the interface and thus can only access the getters, while the creator has full control over it. This requires to have different packages with different visibility, which is probably hard to maintain.

Another way could be (if you are not developing a framework) to make the setters public, but define a general design rule like "Setters may be used by DAOs only". It must be possible to define and communicate such a simple rule to your team to make it work on a long term.

Title: How can a collection class instantiate many objects with one database call?

Body:
I have a baseClass where I do not want public setters. I have a load($id) method that will retrieve the data for that object from the db.

I have been using static class methods like getBy($property,$values) to return multiple class objects using a single database call. But some people say that static methods are not OOP.

So now I'm trying to create a baseClassCollection that can do the same thing. But it can't, because it cannot access protected setters. I don't want everyone to be able to set the object's data. But it seems that it is an all-or-nothing proposition. I cannot give just the collection class access to the setters.

I've seen a solution using debug_backtrace() but that seems inelegant. I'm moving toward just making the setters public.

Are there any other solutions? Or should I even be looking for other solutions?


问:
Why does Clojure neglect the uniform access principle?
My background is Ruby, C#, JavaScript and Java. And now I'm learning Clojure. What makes me feel uncomfortable about the later is that idiomatic Clojure seems to neglect the Uniform access principle (wiki, c2) and thus to a certain degree encapsulation as well by suggesting to use maps instead of some sort of "structures" or "classes". It feels like step back. So a couple of questions, if anyone informed:

Which other design decisions/concerns it conflicted with and why it was considered less important?

Did you have the same concern as well and how it end up when you switched from a language supporting UAP by default (Ruby, Eiffel, Python, C#) to Clojure?

答:
In short: it's considered not valuable enough to bother introducing. Replace a representation and re-factor/modify dependent code when you need it.

From an interview:

Fogus: Following that idea—some people are surprised by the fact that Clojure does not engage in data-hiding encapsulation on its types. Why did you decide to forgo data-hiding?

Hickey [creator of Clojure]: Let’s be clear that Clojure strongly emphasizes programming to abstractions. At some point though, someone is going to need to have access to the data. And if you have a notion of “private”, you need corresponding notions of privilege and trust. And that adds a whole ton of complexity and little value, creates rigidity in a system, and often forces things to live in places they shouldn’t. This is in addition to the other losing that occurs when simple information is put into classes. To the extent the data is immutable, there is little harm that can come of providing access, other than that someone could come to depend upon something that might change. Well, okay, people do that all the time in real life, and when things change, they adapt. And if they are rational, they know when they make a decision based upon something that can change that they might in the future need to adapt. So, it’s a risk management decision, one I think programmers should be free to make.

If people don’t have the sensibilities to desire to program to abstractions and to be wary of marrying implementation details, then they are never going to be good programmers.


问:
GPL Notice on Snippets
Is it ok to put a GPL notice inside a small script or a snippet?

This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

You should have received a copy of the GNU General Public License
  along with this program.  If not, see http://www.gnu.org/licenses/.

Or will just the Copyright notice be enough?

答:
You are correct that you should:

Assert Copyright

Grant people explicit rights to use, modify and distribute your code.

In many places, the idea of public domain is not recognized. In order for someone to be able to (legally) use your code, there must be something that says that they can, and under what conditions. For snippets, I highly recommend the 3 clause BSD style license. It asserts your copyright, tells people that they are free to do whatever they like with the code, so long as they preserve your copyright when distributing it via source and tells them that they can't use your name to endorse derived works of the code without your permission.

The GPL has very specific definitions of what should happen when you combine GPL covered work with something else. The GPL has to prevail as the dominate license in the code base, which means someone using your snippets inherits the GPL. The LGPL (known as the library GPL, or lesser GPL) is more suited for that, because it allows linking without inheriting the license. Still, if you're going to take the teeth out of the GPL, you might as well use a much simpler license.

Another excellent choice would be the MIT license, which is very similar to the three clause BSD style license.

Finally, if you must use the GPL, please indicate "Version 2 or later" if at all possible. This ensures that your code can work in places where a tree might be using "Version 2 Only", which is quite common. A substantial portion of the Linux kernel specifies version 2 only, GPL3 (while widely accepted) was met with a fair amount of criticism and rejection.

I'm not discounting the importance, significance or usefulness of the GPL. I'm just suggesting that it might not be the best choice for snippets and libraries.

Title: GPL Notice on Snippets


问:
How to Implement a Parallel Workflow
I'm trying to implement a parallel split task using a workflow system. I'm using .NET but my process is very simple and I don't want to use WF or anything heavy like that.

I've tried using Stateless. So far is was easy to set up and run, but I may be using the wrong tool for the job because I'm not sure how you're supposed to model parallel split workflows, where you have multiple sub-tasks required before you can advance to the next state, but the steps don't require being performed in any particular order.

I can easily use the dynamic configuration options to check my data model manually to see if the model is in the correct state (all sub-tasks completed) and can transition to the next state, but this seems to completely break the workflow paradigm. What is the proper, orthodox way to implement a parallel split process?

Thanks

答:
In this new answer I will try to explain based on the "Stateless" library mentioned in OP.

Draft.

More information will be added after I get my hands on Stateless.

In any sense, extension to Stateless is required. Fortunately this is highly doable because Stateless is highly extensible using its partial class approach.

A simple description is that:

One business process = a bunch of activities

Each activity requires one StateMachine object. See link to library.

This is necessary because in some circumstances, each activity can have their own state transitions, as explained in "parallel split workflow" by OP.

Some activities are non-trivial (requires an extension to the Stateless library object), which might be implemented in several ways.

One kind of non-trivial activity is to embed (or nest, or delegate to) another business process.

The business process must mediate the state transition rules across all activities, and this requires an extension to the library as well.)

The typical states in a Activity object:

NotConfigured

Only exists programmatically. Compare this to a non-fully-initialized object.

An activity may require some parameters (e.g. for an Email activity, a email address needs to be configured) before this activity can be triggered.

NotNeeded

Indicates that, in its current configuration, this activity does not need to be executed in order for the containing business process to be "completed".

This state is reversible. It can be "reactivated" upon receiving a trigger from another activity.

Example: citizen needs to fill out a SSN. Non-citizen needs to fill out either ITIN or W8-BEN. In either case, one of the activity is not needed. However, if the employee makes a mistake in the option, this mistake should be correctable by clicking a checkbox. This has the effect of deactivating the activity no longer needed, and reactivating the activity now needed.

Succeeded

This state is final (irreversible). Once set into Succeeded, it cannot be set to any other state.

Waiting, with the following substates:

WaitingOnPreconditions

WaitingOnInternalTrigger

WaitingOnBusinessProcess

WaitingOnExternalTrigger

Faulted, with the following substates:

TimedOut,

InternalError

Contains a stack trace (if it is a programmatic error)

Captures a snapshot of the state machines of each activity inside the business process (if it is caused by some invalid state transition requests or mis-configuration of the business process)

ExternalError

Canceled, with the following substates:

CanceledByBusinessProcess (the containing business process is canceled)

CanceledByInternalInvoke (this activity is "nested", and the parent activity requested this to cancel.)

CanceledByUser (by someone with a user ID)

Sometimes, a single activity in human sense must be broken down into multiple activities in software implementation. This will have implications on the design of the Graphical User Interface (GUI). In short - GUI can get very complicated.

Example: a business process modeler will regard "wait for email approval" as one activity. Internally, it is broken down into these activities:

Format email template and send email with email server.

Choice: (both are waiting, but only the first one will become Succeeded, as the other will be promptly set to NotNeeded.)

Wait for approval email reply.

Wait for disapproval email reply.

An exception catcher for timeout.

An exception catcher for anything but timeout (e.g. problem with sending the email, or parsing of the approval/disapproval response)

Displaying all these details on the GUI will make it difficult for the user. Instead, the user should only see options that the user intends to configure.

Almost all interactions (dependencies) between activities are modeled as the "Waiting" state.

WaitingOnPreconditions is the simplest type. Simply speaking, it can wait on final states but not states that flip-flop. Usually, it waits for a set of activities to all transition into the "Succeeded" state. (On the opposite side, it can also wait on "any activity that transitions into the "Faulted" state - this makes it an exception catcher.)

Because the inputs to WaitingOnPreconditions are not allowed to flip-flop, the outcome of WaitingOnPreconditions will also not flip-flop. This is the essential distinction between WaitingOnPreconditions and WaitingOnInternalTrigger, described below.

WaitingOnInternalTrigger is more dynamic than WaitingOnPreconditions. It waits on some observable variables on the business process object to change to a certain value, or some other activities to change their states.

Once entered this state, the activity's StateMachine stays there, unless requested (programmatically) to re-check. The check might be performed with a predicate, Func<bool>, or lambda expression.

The business process object contains some variables that have INotifyPropertyChanged interface. When that event is raised (that is, when the variable value is updated), activities that are in this state (WaitingOnInternalTrigger) will be re-checked.

To avoid indeterminacy or deadlock, the re-check is only allowed to use variables which it can observe. Otherwise, nobody will notify the activity of the relevant changes, and the activity will thus stuck in this state forever.

WaitingOnBusinessProcess is used when an activity embeds another business process. That other business process runs somewhat independently (in software sense), and the current activity will wait for it to finish, cancel, or fault.

WaitingOnBusinessProcess is re-checked whenever the business process it is waiting on has changed state.

WaitingOnExternalTrigger is a mechanism to block the activity until it is unblocked by some other means. For example, it might be waiting on some user interaction, or an approval email. Unblocking is done programmatically - not by another activity or business process.

Every WaitingOnExternalTrigger must have an associated exception catcher (mentioned earlier). This is because all external processes are presumably unreliable, e.g. the employee responsible for this business process might be fired on the spot, (or the email server was struck by a disaster) and thus unable to continue the process.

Other references (not used in my answer)

Homepage of Wil van der Aalst, mentioned as the primary reference for OP's design.

Business Process Model and Notation (BPMN)

Disclaimer: my employer makes BPMN software. However, I do not work in the BPMN product team, and my answer is not representative of my employer's viewpoint. I do not have any privileged knowledge of the BPMN product.

Title: How to Implement a Parallel Workflow


答:
The approach taken by GNU gettext is to defer most of the handling of the various plural forms to the file containing the translations themselves. To retrieve a translated string that might involve pluralization, you make a call like

```<code>ngettext("singular English form", "plural English form", quantity)
</code>```

and the library will select the right plural form based on the value of quantity and the language-specific rules for the various plural forms.

To avoid a combinatorial explosion, this scheme can only handle a single quantity that might trigger pluralisation. If you have multiple quantities that might trigger pluralisation, I would try to either rephrase the message such that the multiple pluralisation is removed or split it into multiple chunks that get translated (and pluralised) separately.

Title: What are common patterns for handling possible pluralization in message properties?

Body:
Obviously users like to see text properly pluralized, and pluralization schemes vary in the various written languages one may encounter.  When internationalizing an app, what pattern(s) are useful for handling messages with possible pluralization?  What about messages with multiple possible pluralization?

For example: "N review(s):"

One pattern would be

```<code>reviews.title.singular="{0} review:"
reviews.title.plural="{0} reviews:"
</code>```

And this may not support all languages.

Or a more complicated case: "Found M question(s) with N comment(s)."

This would be difficult to support even in English.

Body:
The approach taken by GNU gettext is to defer most of the handling of the various plural forms to the file containing the translations themselves. To retrieve a translated string that might involve pluralization, you make a call like

ngettext("singular English form", "plural English form", quantity)

and the library will select the right plural form based on the value of quantity and the language-specific rules for the various plural forms.

To avoid a combinatorial explosion, this scheme can only handle a single quantity that might trigger pluralisation. If you have multiple quantities that might trigger pluralisation, I would try to either rephrase the message such that the multiple pluralisation is removed or split it into multiple chunks that get translated (and pluralised) separately.


答:
The only way to do it is to move away from a perception of code review as a "review" of what someone did, to an information-passing system. So instead of the reviewer driving the review and critiquing the developer's code, the developer drives the review to teach the reviewer what (and why) he did.

Ultimately the same result is achieved, but in a way that has far less negative connotations.

Title: How to make code-review feel less like a way to *shift* the responsibility?

Body:
Sometimes it seems to me that people ask for code-reviews just so they would be able to say "Xyz reviewed my code!"(1) when something broke.

Question, is that ever the case? (Or is it just my imagination)
If it is, how do I handle this?

(1): What s/he really meant: It's Xyz's fault or something along those lines.


答:
Solutions like the ones described in the other answers may work, but are IMO quite complicated to implement when you're dealing with a great number of different phrases, several pluralized words in the same phrase and so on.

It gets even worse when you have languages with more complex plural rules, as described here.

At work, we're dealing with stuff like this as well (in 5 languages, for now).

What we do: We try to avoid all that complexity by writing our messages either exactly like the examples in your question:

Found M question(s) with N comment(s).

...or like this:

Number of questions found: M

  Number of comments found: N

Of course this doesn't look as elegant as the output of the more complex solutions, but it's much, much easier to deal with.


问:
Should you always pass the bare minimum data needed into a function in cases like this
Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important).

In my head there are then two possible function signatures for this:

```<code>public bool IsAdmin(User user);
public bool IsAdmin(int id, string name, string password);
</code>```

I most often go for the second type of signature, thinking that:

The function signature gives the reader a lot more info

The logic contained inside the function doesn't have to know about the User class

It usually results in slightly less code inside the function

However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object.

I would appreciate any arguments for either style, as well as any general observations you might offer.

I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.

答:
The first signature is superior because it allows the encapsulation of user-related logic in the User object itself.  It is not beneficial to have logic for the construction of the "id, name, password" tuple strewn about your code base.  Furthermore, it complicates the isAdmin function: what happens if someone passes in an id that does not match the name, for example?  What if you want to check if a given User is an administrator from a context where you should not know their password?

Furthermore, as a note on your third point in favor of the style with extra arguments; it may result in "less code inside the function," but where does that logic go? It can't just vanish! Instead, it's spread around every single place where the function is called. To save five lines of code in a single place, you've paid five lines per use of the function!


答:
I personally prefer the first method of just IsAdmin(User user)

It's much easier to use, and if your criteria for IsAdmin changes at a later date (perhaps based on roles, or isActive), you don't need to rewrite your method signature everywhere.

It's also probably more secure as you aren't advertising what properties determine if a user is an Admin or not, or passing around the password property everywhere. And syrion makes a good point that what happens when your id doesn't match the name/password?

The length of code inside a function shouldn't really matter providing the method does its job, and I'd much rather have shorter and simpler application code than helper method code.

Title: Should you always pass the bare minimum data needed into a function in cases like this

Body:
Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important).

In my head there are then two possible function signatures for this:

```<code>public bool IsAdmin(User user);
public bool IsAdmin(int id, string name, string password);
</code>```

I most often go for the second type of signature, thinking that:

The function signature gives the reader a lot more info

The logic contained inside the function doesn't have to know about the User class

It usually results in slightly less code inside the function

However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object.

I would appreciate any arguments for either style, as well as any general observations you might offer.

I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.


答:
The first, but not (only) for the reasons others have given.

```<code>public bool IsAdmin(User user);
</code>```

This is type safe.  Especially since User is a type you defined yourself, there is little or no opportunity to transpose or switch up arguments.  It clearly operates on Users and is not some generic function accepting any int and two strings.  This is a big part of the point of using a type-safe language like Java or C# which your code looks like.  If you are asking about a specific language, you might want to add a tag for that language to your question.

```<code>public bool IsAdmin(int id, string name, string password);
</code>```

Here, any int and two strings will do.  What prevents you from transposing the name and password?  The second is more work to use and allows more opportunity for error.

Presumably, both functions require that user.getId(), user.getName(), and user.getPassword() be called, either inside the function (in the first case) or before calling the function (in the second), so the amount of coupling is the same either way.  Actually, since this function is only valid on Users, in Java I would eliminate all arguments and make this an instance method on User objects:

```<code>user.isAdmin();
</code>```

Since this function is already tightly coupled to Users, it makes sense to make it a part of what a user is.

P.S. I'm sure this is just an example, but it looks like you are storing a password.  You should instead only store a cryptographically secure password hash.  During login, the supplied password should be hashed the same way and compared against the stored hash.  Sending passwords around in plain-text should be avoided.  If you violate this rule and isAdmin(int Str Str) were to log the user name, then if you transposed the name and password in your code, the password could be logged instead which creates a security issue (don't write passwords to logs) and is another argument in favor of passing an object instead of its component parts (or using a class method).

Body:
The first, but not (only) for the reasons others have given.

public bool IsAdmin(User user);

This is type safe.  Especially since User is a type you defined yourself, there is little or no opportunity to transpose or switch up arguments.  It clearly operates on Users and is not some generic function accepting any int and two strings.  This is a big part of the point of using a type-safe language like Java or C# which your code looks like.  If you are asking about a specific language, you might want to add a tag for that language to your question.

public bool IsAdmin(int id, string name, string password);

Here, any int and two strings will do.  What prevents you from transposing the name and password?  The second is more work to use and allows more opportunity for error.

Presumably, both functions require that user.getId(), user.getName(), and user.getPassword() be called, either inside the function (in the first case) or before calling the function (in the second), so the amount of coupling is the same either way.  Actually, since this function is only valid on Users, in Java I would eliminate all arguments and make this an instance method on User objects:

user.isAdmin();

Since this function is already tightly coupled to Users, it makes sense to make it a part of what a user is.

P.S. I'm sure this is just an example, but it looks like you are storing a password.  You should instead only store a cryptographically secure password hash.  During login, the supplied password should be hashed the same way and compared against the stored hash.  Sending passwords around in plain-text should be avoided.  If you violate this rule and isAdmin(int Str Str) were to log the user name, then if you transposed the name and password in your code, the password could be logged instead which creates a security issue (don't write passwords to logs) and is another argument in favor of passing an object instead of its component parts (or using a class method).


答:
If your language of choice doesn't pass structures by value, then (User user) variant seems better. What if someday you decide to scrap the username and just use the ID/password to identify the user?

Also, this approach inevitably leads to long and overblown method calls, or inconsistencies. Is passing 3 arguments okay? How about 5? Or 6? Why think of that, if passing an object is cheap in terms of resources (even cheaper than passing 3 arguments, probably)?

And I (sort of) disagree that the second approach gives the reader more info - intuitively, the method call is asking "whether the user has admin rights", not "whether the given id/name/password combination has admin rights".

So, unless passing the User object would result in copying a large structure, the first approach is cleaner and more logical to me.


问:
What are some Java patterns well-suited for fast, algorithmic coding?
I'm in college, and I've recently started competing in programming competitions with my friends. These competitions involve solving algorithmic problems quickly. It's a lot of fun, but there's one problem: I'm forced to use Java. (My teammates use Java.)

Background: I'm a self-taught JavaScript programmer, and it hurts to write Java code. I find it very verbose and inflexible, and I feel slowed down when having to declare types and decide which of the eighty list data structure to use. I'm also frustrated about the lack of functional programming features and how verbose using regular expressions, arrays, and dictionaries are.

As an example, consider the problem of finding the length of the longest string of consecutive characters in a given string. So the string XX22BBBBccXX222 would give 4, for the string of four Bs. In Java, I'd have to loop through and manually count characters and manually keep track of the maximum. (That's at least as far as I'm aware -- I'm not as familiar with Java as I am with JavaScript.) In JavaScript, I'd find it like this:

```<code>var max = Math.max.apply(Math, str.match(/(.)\1*/g).map(function (s) { return s.length; }));
</code>```

Much quicker and simpler, in my book.

The question: what are some Java features, techniques, or patterns well-suited for fast, algorithmic coding?

答:
I used to do a few programming competitions, and found that the most important things to know were:

The full APIs of your collection classes. Stacks, Sets, Maps and Queues are pretty critical to many algorithms.

All of the String processing tricks (regexes, string joining, parsing etc.). This is because Strings are often used as inputs / data types to manipulate

All of the variations of looping / iteration constructs - again these come up so frequently, you want to be able to select the right one and use it pretty much automatically.

Features of your IDE. Code completion, type checking, unit testing etc are very useful if you want to write code quickly while also being 99% confident that it is correct. The compiler/IDE can help you a lot.


问:
How to support a product built with agile development?
Two of the functions our company provides our customers are:

Our Development team of ~10 employees creates software products for businesses in a particular industry. The software is used on hundreds of our customers' computers. Although the product is, for most customers, off-the-shell, larger customers drive its development, so it's somewhere between shrinkwrap software and custom software.

Our Support team of ~25 employees provides technical support for both our own software and a few other software products for which we are the vendor.

Our Development team recently switched to Scrum for their development methodology, and while I support this change, I worry that our Support team is going to have more trouble in the future.  With a quicker release cycle, our customers will have features and products in production which Support isn't even aware of until the customer calls. We've never been particularly good at getting documentation and information from Development to Support, but I fear Scrum will just exacerbate the problem.

What are good references on how companies reconcile Development's desire to release frequently with Support's desire to have full documentation and support information before customers see the product?  How should a company structure their release and change management when using agile methods?

EDIT: What I'm interested are specifics on how companies structure themselves to deal with these issues. Does the scrum team push releases to customers? Does the software have to go through a release/change management team who will not deploy until Support has been given documentation and brought up to speed?  How do you get releases to customers quickly yet still keep everyone informed of changes and new features?

答:
You may already have the data available to help communicate to your support team.

If you have a ticketing system to track bugs and feature requests, you can easily provide automated reports when tickets are resolved.

Likewise your source control system can used to deliver a changelog for each release with each atomic checkin ("ie: Bug #12345 fixed").

If you don't have any of the systems above, you've got other problems waiting to happen.

During your product testing phase (after code is changed, before it is released), this is the ideal time to produce changelogs and communicate with support staff. During this time don't bombard them with huge lists, just give them an itemised list of features and bugs that have been addressed - and provide links to the appropriate systems.

If you don't have dedicated testers - I'd consider pulling one of your longer-term support guys into such a role - they'll help you release less-buggy code and can make sure someone is responsible for putting together documentation for the support team.

Just a few thoughts :)


问:
Turning a problem into a data
OK, I have an app that I'm creating but I'm just really not sure about how to approach the problem.

The idea is fairly simple. I'm just not sure how to wrap it in a data model (or even if I should). TBH I feel like I'm making it more complicated than it needs to be.

How it works.

The app will have circles along the top in a row that need to be connected to circles along the bottom in a row.
10 circles at the top. 10 at the bottom. One connection per pair of dots.

Anyway, I can get the dots to connect I'm just not sure how to wrap it in a data model so that I can analyse what has been connected and see if it is right or not.

The circles will be questions and answers.

I can make an array of question objects with a question and answer properties.
I can then display these as the dot pairs.
I'm just not sure how to record which questions have been connected to which answers.

It is valid for a user to connect a wrong answer as they all get checked at the end.

I was thinking of using SpriteKit but this isn't a restriction. I could use UIKit or something else. TBH, this question is fairly language free as I'm just after a way of modelling it.

答:
I'd do it with a pair of dictionaries which are lists of key-value pairs. The keys in this case are the questions and the values are the answers.

You'd have one dictionary that is the "Correct" dictionary for a given question set. You'd then have a dictionary that gets filled as the user selects question and answer pairs. Once they have selected all the question and answer pairs, you simply test the dictionaries against each other. If they are the same then the user is correct and you can go from there.

Title: Turning a problem into a data


问:
JSP Include: one large bean or bean for each include
I want to refactor a webapp that consists of very distorted JSPs and servlets. Because we can't switch to a web framework easily we have to keep JSPs and Servlets, and now we are in doubt how to include pages into another and how to setup the use:bean-directives effectively.

At the first step we want to decouple the code for the core-actions and the bean-creation into servlets. The servlets should forward to their corresponding pages, which should use the bean. The problem here is, that each jsp consists of different sub- and sub-sub-jsp that are included into another. Here is a shortend extract (because reality is more complex):

head

header

top

navigation

actionspanel

main

header

actionspanel

foot

footer

Moreover each jsp (also the header and footer) use dynamic data. For example title and actionspanel can change on each page-reload or do have links and labels that depend on the processing by the preceding servlet.

I know that jsp-include-directives should only be used for static content und should be avoided for dynamic content. But here we have very large pages, that consist of many parts.

Now the core questions:
Should I use one big bean for each page, so that each bean holds also data for header and footer beside its core data, so that each subsequent included jsp uses the same bean-directive? For example:

DirectoryJSP <-> DirectoryBean

CompareJSP <-> CompareBean

Or should I use one bean for each jsp, so that each bean only holds the data for one jsp and its own purpose. For example:

DirectoryJSP <-> DirectoryBean

HeaderJSP <-> HeaderBean

FooterJSP <-> FooterBean

CompareJSP <-> CompareBean

HeaderJSP <-> HeaderBean

FooterJSP <-> FooterBean

In the second case: should the subsequent beans be a member of the corresponding parent bean, so that only the parent bean is attached as attribute to the request? Or should each bean attached to the request?

答:
If all pages have same header (and footer), change in one Headerbean should propagate the change to all JSPs. Similarly, Change in one page specific logic should only be effecting one bean. Also refactor common code out of beans into other POJOs.

Just aim for for high cohesion and low coupling.


答:
The core of the problem is that you're not as familiar with Java as your friends.

Rather than try to look for a generic solution, I'd say the best solution here is the same as when trying to learn a language or codebase in other situations:  More exposure.

In this case, the simplest thing would be to look at your friend's solutions to see what patterns they used, but might not be the most effective.

Another approach would be to take your Javascript and break it down into a more iterative form.  For example:

```<code>Math.max.apply(Math, str.match(/(.)\1*/g).map(function (s) { return s.length; }));
</code>```

There's 3 core conceptual pieces to this:

The regex for finding groupings

Converting each group to a length

Finding the maximum

Individually they're all pretty easy.  Java has support for regex groups, all you need is a simple loop to get the lengths, and finding the maximum is just as easy.  It can even be made simpler by combining those last two in Java - since all you need for output is the number, all you need is a single variable to hold the end result, rather than an entire array for all the string lengths.

Title: What are some Java patterns well-suited for fast, algorithmic coding?

Body:
I'm in college, and I've recently started competing in programming competitions with my friends. These competitions involve solving algorithmic problems quickly. It's a lot of fun, but there's one problem: I'm forced to use Java. (My teammates use Java.)

Background: I'm a self-taught JavaScript programmer, and it hurts to write Java code. I find it very verbose and inflexible, and I feel slowed down when having to declare types and decide which of the eighty list data structure to use. I'm also frustrated about the lack of functional programming features and how verbose using regular expressions, arrays, and dictionaries are.

As an example, consider the problem of finding the length of the longest string of consecutive characters in a given string. So the string XX22BBBBccXX222 would give 4, for the string of four Bs. In Java, I'd have to loop through and manually count characters and manually keep track of the maximum. (That's at least as far as I'm aware -- I'm not as familiar with Java as I am with JavaScript.) In JavaScript, I'd find it like this:

```<code>var max = Math.max.apply(Math, str.match(/(.)\1*/g).map(function (s) { return s.length; }));
</code>```

Much quicker and simpler, in my book.

The question: what are some Java features, techniques, or patterns well-suited for fast, algorithmic coding?

Body:
The core of the problem is that you're not as familiar with Java as your friends.

Rather than try to look for a generic solution, I'd say the best solution here is the same as when trying to learn a language or codebase in other situations:  More exposure.

In this case, the simplest thing would be to look at your friend's solutions to see what patterns they used, but might not be the most effective.

Another approach would be to take your Javascript and break it down into a more iterative form.  For example:

Math.max.apply(Math, str.match(/(.)\1*/g).map(function (s) { return s.length; }));

There's 3 core conceptual pieces to this:

The regex for finding groupings

Converting each group to a length

Finding the maximum

Individually they're all pretty easy.  Java has support for regex groups, all you need is a simple loop to get the lengths, and finding the maximum is just as easy.  It can even be made simpler by combining those last two in Java - since all you need for output is the number, all you need is a single variable to hold the end result, rather than an entire array for all the string lengths.


问:
How best to look up objects by label?
I am writing the server backed by a pre-written API.  I'm going to get a number of strings representing ports, signals, paths, etc etc etc.  I need to look up the object associated with a given label, these objects are all in memory (no sql magic to do this for me).

My question is, how best do I associate a given unique label with the mutable object it represents?  I have enough objects that looking through every signal or every port to find the one that matches is possible, but may be slightly too slow.

To be honest the direct 'look at every object' method is probably good enough for so small a body of objects and anything else is premature optimization, but I still am curious what the proper solution would be if I thought my signals were going to grow a bit larger.  As I see it there are two options available.

First would be to to create a 'store' that is a simple map between object and label.  I could have it so that every time I call addObject the object is automatically saved into a hashmap or the like.  This works, but relies on my properly adding and deleting each object so the map doesn't grow indefinitely.  The biggest issue to me is that this involves having some hidden static map in my ModelObject class that just feels...wrong somehow.

The other option is to have some method that can interpret the labels.  All of these labels are derived from the underlying objects.  So I can look at the signal label, for instance, and say "these 20 characters are the port" to figure out what port I need.  This would allow me to quickly figure out what I need.  However, if the label method is changed the translateLabelToObject method needs to be updated as well or everything breaks.

Which solution is cleaner, or possibly a cleaner solution than either of above?

For the record I'm working with sufficient number of variables to make direct comparison a little slow, but not enough to be concerned about memory overhead, written in java.  All objects that have labels I need to look up extend the same parent class.

答:
Since you say "these objects are all in memory", see if LinkedHashMap with accessOrder=true is what you need.

Also if ModelObject doesn't seem like the right class then just make the right class to have this info: perhaps ModelStore (a singleton?)

Title: How best to look up objects by label?


问:
Are VB.NET to C# converters actually compilers?
Whenever I see programs or scripts that convert between high-level programming languages they are always labelled as converters.

"VB.NET to C# converter" on Google results in expected, useful hits.

However "VB.NET to C# compiler" on Google results in things like comparisons between the C# and VB.NET compilers and other hits that are not quite what you'd be looking for.

Webopedia defines Compiler as

A program that translates source code into object code

Eric Lipper in an answer to: "How do I create my own programming language and a compiler for it" suggests:

One of the best ways to get started writing a compiler is by writing a high-level-language-to-high-level-language compiler.

Is a VB.NET to C# converter really just a compiler? If not, What separates the converter from also being a compiler?

答:
Depending on how you look at it, maybe the difference between a "converter" and a "compiler" kind of comes down to the objectives involved in one versus the other.

Do a "converter" and a "compiler" both perform lexical analysis and convert one flavor of code into another?  Sure they do.  But with totally different objectives.

You're going to use a "converter" to transform source code from one portable high-level language syntax to another portable high-level language syntax, so that you can maintain your source code in a different language, right?

The goal is that you end up with your source code base in C# instead of VB.NET.  Maybe you just don't like VB.NET syntax, maybe all of your other source code is in C# and you want a uniform code base, maybe you have some VB.NET code which is perfectly fine except that you want to have your product run on mono.  Maybe all sorts of things.  Actually, it looks like there is a VB compiler in the works for Mono.  Why, I really can't imagine.  VB was great back in the day.  R.I.P., VB.

So the work result of a converter, in the context we seem to be talking about, is maintainable, portable high-level source code that you'll put into your source code repository and make your team embrace, extend and maintain.

On the other hand, the work result of a compiler is executable, probably optimized and almost certainly non-maintainable and non-portable code that targets a specific CPU. The work result of a compiler is executable code.

Granted, I'm conflating the concepts of compilers and linkers here.  But so did at least one of the commenters who referred to the C#/VB.NET compilers producing IL, which then needs to be "compiled" into executable code.  :-)

.NET has a sort of fancy extra layer, where the "compiler" transforms your C# or VB (or F# or Eiffel or JScript or managed C++ or...) code into an IL assembly (an .exe or .dll file), and then when you "run" that code, the .NET JIT (Just-In-Time compiler) intervenes, magically and transparently converting your IL into native non-portable code for whatever CPU it finds itself running on.  Or you can use ngen to convert your IL assembly into a native image for a particular CPU ahead of time (though the benefits may not be as dramatic as you hope).

So, via whatever circuitous route, the work product that is ultimately squirted out by a VB.NET to C# converter will be to take a source code file containing something like:

```<code>Dim i As Integer
For i = 1 To 100
   ' do something
Next
</code>```

And convert it to something like this:

```<code>for( int i = 1; i <= 100; i++ )
    {
    // do something
    }
</code>```

You'll store that resulting C# source code in your source code repository and use a compiler to turn that into executable code for distribution to your customer.  And you get to program in C# instead of VB.

Note, by the way, some of the subtle difference in instinctive thinking that accompanies VB programming versus C# (C/C++) programming, where that loop iteration started at 1 instead of zero.

IL is really just a sort of CPU-agnostic assembly language.  Unless you have some esoteric low-level, system-programmer reason to be maintaining code in IL, you just aren't ever going to be storing the stuff in your source code repository.  Other times you might fiddle with IL are when you're actually a language programmer on the Microsoft .NET team or the Mono team or some other language team that makes a .NET compiler for a specific language (FORTRAN or COBOL, anyone?), or you are deep into debugging some weird edge case and use a disassembler on your own code, or you're trying to resolve a technical argument with another developer on your team who you know is crazily wrong about something (never happens, right?), or you're inspecting somebody else's IL assembly to try to figure out how it works or whether it is safe to call it in a certain way.

That isn't so different from the uses of traditional CPU-specific assembly language (or assembler for discrete systems like the old mainframes and mini's before there really were all-in-one silicon CPU's).  "High level" languages like LISP, COBOL, FORTRAN and C (which was originally billed as a sort of portable assembly language) were developed to make code easier for mere humans to grasp, and to make it possible to compile the same code to run on more than one type of computer.  So a C compiler takes "high-level" C source code and turns it into assembly language for whatever CPU you're compiling for, and then you use a linker (which is usually automatically invoked by your compiler) to further transform that into actual binary code that you can shove straight through the CPU.  But the compiler results aren't the thing that you keep around as "source" code, right?

Well, I do remember a case years ago where a team of developers had a set of "magic *.obj files" that they had to link against because the original source code had been lost somehow.  But I digress...

It is entirely reasonable to assume that some .NET converters might actually work by "compiling" code into IL, then "decompiling" the resulting IL back into another language.  At least a few of the IL disassemblers floating around do essentially that (including .NET Reflector and ILSpy).  But the objective is still different from what a "compiler" does, right?

So I contend that a converter is not really just a compiler by another name.

Body:
Depending on how you look at it, maybe the difference between a "converter" and a "compiler" kind of comes down to the objectives involved in one versus the other.

Do a "converter" and a "compiler" both perform lexical analysis and convert one flavor of code into another?  Sure they do.  But with totally different objectives.

You're going to use a "converter" to transform source code from one portable high-level language syntax to another portable high-level language syntax, so that you can maintain your source code in a different language, right?

The goal is that you end up with your source code base in C# instead of VB.NET.  Maybe you just don't like VB.NET syntax, maybe all of your other source code is in C# and you want a uniform code base, maybe you have some VB.NET code which is perfectly fine except that you want to have your product run on mono.  Maybe all sorts of things.  Actually, it looks like there is a VB compiler in the works for Mono.  Why, I really can't imagine.  VB was great back in the day.  R.I.P., VB.

So the work result of a converter, in the context we seem to be talking about, is maintainable, portable high-level source code that you'll put into your source code repository and make your team embrace, extend and maintain.

On the other hand, the work result of a compiler is executable, probably optimized and almost certainly non-maintainable and non-portable code that targets a specific CPU. The work result of a compiler is executable code.

Granted, I'm conflating the concepts of compilers and linkers here.  But so did at least one of the commenters who referred to the C#/VB.NET compilers producing IL, which then needs to be "compiled" into executable code.  :-)

.NET has a sort of fancy extra layer, where the "compiler" transforms your C# or VB (or F# or Eiffel or JScript or managed C++ or...) code into an IL assembly (an .exe or .dll file), and then when you "run" that code, the .NET JIT (Just-In-Time compiler) intervenes, magically and transparently converting your IL into native non-portable code for whatever CPU it finds itself running on.  Or you can use ngen to convert your IL assembly into a native image for a particular CPU ahead of time (though the benefits may not be as dramatic as you hope).

So, via whatever circuitous route, the work product that is ultimately squirted out by a VB.NET to C# converter will be to take a source code file containing something like:

Dim i As Integer
For i = 1 To 100
   ' do something
Next

And convert it to something like this:

for( int i = 1; i <= 100; i++ )
    {
    // do something
    }

You'll store that resulting C# source code in your source code repository and use a compiler to turn that into executable code for distribution to your customer.  And you get to program in C# instead of VB.

Note, by the way, some of the subtle difference in instinctive thinking that accompanies VB programming versus C# (C/C++) programming, where that loop iteration started at 1 instead of zero.

IL is really just a sort of CPU-agnostic assembly language.  Unless you have some esoteric low-level, system-programmer reason to be maintaining code in IL, you just aren't ever going to be storing the stuff in your source code repository.  Other times you might fiddle with IL are when you're actually a language programmer on the Microsoft .NET team or the Mono team or some other language team that makes a .NET compiler for a specific language (FORTRAN or COBOL, anyone?), or you are deep into debugging some weird edge case and use a disassembler on your own code, or you're trying to resolve a technical argument with another developer on your team who you know is crazily wrong about something (never happens, right?), or you're inspecting somebody else's IL assembly to try to figure out how it works or whether it is safe to call it in a certain way.

That isn't so different from the uses of traditional CPU-specific assembly language (or assembler for discrete systems like the old mainframes and mini's before there really were all-in-one silicon CPU's).  "High level" languages like LISP, COBOL, FORTRAN and C (which was originally billed as a sort of portable assembly language) were developed to make code easier for mere humans to grasp, and to make it possible to compile the same code to run on more than one type of computer.  So a C compiler takes "high-level" C source code and turns it into assembly language for whatever CPU you're compiling for, and then you use a linker (which is usually automatically invoked by your compiler) to further transform that into actual binary code that you can shove straight through the CPU.  But the compiler results aren't the thing that you keep around as "source" code, right?

Well, I do remember a case years ago where a team of developers had a set of "magic *.obj files" that they had to link against because the original source code had been lost somehow.  But I digress...

It is entirely reasonable to assume that some .NET converters might actually work by "compiling" code into IL, then "decompiling" the resulting IL back into another language.  At least a few of the IL disassemblers floating around do essentially that (including .NET Reflector and ILSpy).  But the objective is still different from what a "compiler" does, right?

So I contend that a converter is not really just a compiler by another name.


问:
Should my colleagues review each others code from source control system?
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.

答:
I would say YES!

Two quick reasons for it:

1) If code is in production, you cannot assume that it is correct. Any change elsewhere in the system can introduce bugs. I think it is very important that code be checked regularly. This way, refactoring is done on a regular basis, keeping the code neat and "more" correct (up to date is probably bettter).

2) Being able to read code is a very important skill if you are going to be a programmer. And a skill it is, something you need to work on. For any programmer starting work on an existing code base, if he is not used to reading other people's code, there is a steep learning curve trying to get up to date with what is going on.

I do not think you should feel spied on. Accept any critique someone gives you (if it is valid of course). And feel free to give other people VALID critique. It is the way we learn. Once we stop learning (or want to stop), then there are big problems.


问:
Is it necessary to use "-" or "+" before every property or method declaration in Interface and why?
I'm new to objective C, I'm following "Objective C 5th Edition Stephen Kochan and I don't have anyone to ask my doubts to. I'm confused with this question:

Q. Is it necessary to use "-" or "+" before every property or method declaration in Interface? What will happen if I don't use "-" or "+" before every property or method declaration in Interface?

答:
Yes it is necessary to declare the method type specifier, if you don't declare those method types, you will receive a red warning telling you that you need to specify the method type.

Also it is recommended to assign the method type specifier in order to see which methods are class methods, and which ones are instance methods.

The "-" sign indicates an instance method.

The "+" sign indicates a class method.


答:
I would probably have both. The first one as an external API, with some hope of stability in time. The second one as a private implementation called by the external API.

If at some later time I have to change the checking rule, I would just write a new private function with a new signature called by the external one.

This has the advantage of easyness to change inner implementation. Also it's really usual that at some time you may need both functions available at the same time and call one or the other depending of some external context change (for instance you may have coexisting old Users and new Users with different fields).

Regarding the title of the question, in a way in both cases you are providing the minimum necessary information. A User seems to be the smallest Application Related Data Structure containing the information. The three fields id, password and name seems to be the smallest implementation datas actually needed, but these are not really Application level object.

In other words If you were dealing with a database a User would be a record, while id, password and login would be fields in that record.