问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答:
Not all users have usable internet access.  For example, outside of small and medium cities (and their suburbs) and university towns, the US has almost no broadband infrastructure.  Small town and rural users are generally on satellite or dialup (and their phone lines aren't always the best, so dialup is often below 50k/s).

Users with good internet access at home/office often operate in other places: parks, airplanes, cafes, conference venues, etc. that usually lack reliable internet access.

Many users invest in back-up power for a reason: so they don't experience down time during outages.  If you cripple your application when the internet goes down, you've just robbed them of that investment.

Internet connections fail, ISPs (or workplaces, or universities) block traffic at their own whim, home users misconfigure their NATs... it is just plain stupid to create an artificial (i.e. not a technical consequence of building the thing) point of failure in your software.

The above reasons alone are more than enough not to use the "call home" DRM model; but even if none of them were true, I'd still advise against it because, as Mason already tried to point out, it is ethically wrong to exploit your users in this way.

You don't get to expose information about your users just for the sake of your own piece of mind.  You have no right to monitor when and from where they use your software.  Doing this sort of thing violates your users' trust.


问:
Avoiding a large amount of overloads
I'm currently writing a mailing interface for our enterprise application. Dependent on the send mode (regular email, bulk email, templates, mailmerge, ...) our Send() method requires a bunch of parameters.

Now we have got this Send() method that offers to take around 20 parameters, with nearly 10 overloads and default values.

Now of course you could use the C# 4.0 feature of named parameters like described here, but even that would be a mess when mostly 10 of 15 overloaded parameters have to be used.

Is there some better practice?

答:
It looks like your Send() method is doing too much and asking for too much information.

What happens when it has to deal with a template or mail merge? Is it really sending something? I don't think so, and so Send is a badly chosen name. But it's not the choice of the name which is bad here, but, again, the fact that Send() does too much: it sends e-mails, stores templates or does a mail merge and stores the results in a database (I suppose).

When you split the method into several smaller ones, your Send() one becomes smaller:

```<code>public void Send() // Actually sends regular e-mails or bulk e-mails.
public void StoreTemplate()
public void DoMailMerge()
</code>```

Let's get back to Send(). If it still has too many arguments, you are possibly giving it configuration information. Instead, this information should either be loaded from a configuration file or be passed through properties to the instance of the object containing Send().

Instead of:

```<code>sender.Send(from, bulkTo, title, body, timeout, mailsPerSecond);
</code>```

you should be doing:

```<code>sender.bulkMailsPerSecond = this.mailsPerSecond;
sender.Send(bulkTo, title, body);
</code>```

given that:

from is now in the configuration, loaded directly by Sender when needed,

timeout becomes a property of Sender with a default value.

The next step is to reduce the size of Sender: you may end up noticing that the class is too large and doing too much. For example, you may end up exporting templating-related stuff in a separate class, or use inheritance in order to apply custom logic for regular e-mails and bulk e-mails:

```<code>public abstract class Sender
{
    protected Address From { get { ... } }
    protected TimeSpan Timeout { get { ... } set { ... } }
}

public class RegularEmailSender : Sender
{
    public void Send(Address to, string title, string body) { ... }
}

public class BulkEmailSender : Sender
{
    private int BulkMailsPerSecond { get { ... } set { ... } }
    public void Send(IEnumerable<Address> bulkTo, string title, string body) { ... }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Avoiding a large amount of overloads

Body:
It looks like your Send() method is doing too much and asking for too much information.

What happens when it has to deal with a template or mail merge? Is it really sending something? I don't think so, and so Send is a badly chosen name. But it's not the choice of the name which is bad here, but, again, the fact that Send() does too much: it sends e-mails, stores templates or does a mail merge and stores the results in a database (I suppose).

When you split the method into several smaller ones, your Send() one becomes smaller:

public void Send() // Actually sends regular e-mails or bulk e-mails.
public void StoreTemplate()
public void DoMailMerge()

Let's get back to Send(). If it still has too many arguments, you are possibly giving it configuration information. Instead, this information should either be loaded from a configuration file or be passed through properties to the instance of the object containing Send().

Instead of:

sender.Send(from, bulkTo, title, body, timeout, mailsPerSecond);

you should be doing:

sender.bulkMailsPerSecond = this.mailsPerSecond;
sender.Send(bulkTo, title, body);

given that:

from is now in the configuration, loaded directly by Sender when needed,

timeout becomes a property of Sender with a default value.

The next step is to reduce the size of Sender: you may end up noticing that the class is too large and doing too much. For example, you may end up exporting templating-related stuff in a separate class, or use inheritance in order to apply custom logic for regular e-mails and bulk e-mails:

public abstract class Sender
{
    protected Address From { get { ... } }
    protected TimeSpan Timeout { get { ... } set { ... } }
}

public class RegularEmailSender : Sender
{
    public void Send(Address to, string title, string body) { ... }
}

public class BulkEmailSender : Sender
{
    private int BulkMailsPerSecond { get { ... } set { ... } }
    public void Send(IEnumerable<Address> bulkTo, string title, string body) { ... }
}


问:
Web API Design advice
I am developing a Web API as services layer for a ASP.NET web forms application.

There are two controllers ContractorController (gives details about the contractor) and PaymentsController (gives details about payments done to a contractor).

Now in our UI application we have this User-Control which will be used across many pages:

Is the responsibility of the UI to call the ContractorController and PaymentsController separately to get the required data? Or should I provide a Consolidated Method (may be on PaymentsController) to give back all the required data, which seems to be going against RESTful approach or dealing with resources?

Thank you.

答:
I would make it this way:

Encapsulate this UI piece into a component, that is responsible only for UI part of the job. Upon construction this component needs data about both contractor and payments to be provided to it (via constructor, some setter methods - whatever. Depends on your design)

Encapsulate database-related logic into two services (ContractorService and PaymentService). Those services can fetch data from database using conditions you provide and prepare it (convert types, fill related object instances, localize via calls to LocalizationService etc).

Now in any controller action (e.g. in any section /page of your website regardless of how controller is called) you first call respected services to fetch the data and then feed this data into your UI component.

Title: Web API Design advice


答:
From your comments it seems you have something like this:

```<code>Send(Data data, Address address, A a, B b, C c) { ... }

Send(Data data, Address address, A a, D d, E e, F f) { ... }

Send(Data data, Address address, B b, H h, J j) { ... }
</code>```

Where A, B, C, ... are types of values used for configuration. You're implicitly working with a Configuration type that can come in a finite set of "shapes" or combinations. You want a tagged union, but C# doesn't support them directly. However, you can implement one with inheritance. The key is to recognize that you can create an abstract class that has a finite set of subclasses by:

Giving the abstract class a private constructor.

Making the subclasses inner sealed classes of the abstract class.

The inner subclasses have access to the abstract class's private constructor, but top-level classes don't, so no one can add a new subclass "from the outside".

So you'd have something like this:

```<code>abstract class Configuration {
    private Configuration() {
        // Prevent outside subclassing
    }

    public sealed class Conf1 : Configuration {
         public A a { get; set; }
         public B b { get; set; }
         public C c { get; set; }

         // Constructor boilerplate
    }

    public sealed class Conf2 : Configuration {
         // Different fields
         // Constructor boilerplate
    }

    // ... more subclasses
}
</code>```

(I don't work with C# regularly; hopefully I haven't made any serious syntax mistakes.)

Then all you need is a safe way to examine which kind of Configuration subclass you got. This is essentially the visitor pattern, but you can make it more concise with delegates:

```<code>abstract class Configuration {
    ...
    public abstract R Match<R>(Func<Conf1, R> ifConf1, Func<Conf2, R> ifConf2, ...);
    ...
    public sealed class Conf1 : Configuration {
        ...
        public override R Match<R>(...) {
            // Each subclass calls the delegate corresponding to it
            return ifConf1(this);
        }
        ...
    }

    // And so on with every other subclass
 }
</code>```

Now you can reduce your Send to:

```<code>Send(Data data, Address address, Configuration config) {
    return config.Match(
        ifConf1: conf1 => { ... },
        ifConf2: conf2 => { ... },
        ...
    );
}
</code>```

This all assumes that the number of combinations of configuration values is limited and doesn't change terribly often. I've assumed that, for example, all the Send methods use the same underlying mechanism and that it can simply be configured in a variety of ways. If you wanted to abstract over different kinds of sending services (e.g. e-mail vs some sort of IPC vs SOAP) then I'd use an interface similar to MainMa's Sender class since that solution always allows you to add new kinds of "senders" easily.

Title: Avoiding a large amount of overloads

Body:
I'm currently writing a mailing interface for our enterprise application. Dependent on the send mode (regular email, bulk email, templates, mailmerge, ...) our Send() method requires a bunch of parameters.

Now we have got this Send() method that offers to take around 20 parameters, with nearly 10 overloads and default values.

Now of course you could use the C# 4.0 feature of named parameters like described here, but even that would be a mess when mostly 10 of 15 overloaded parameters have to be used.

Is there some better practice?

Body:
From your comments it seems you have something like this:

Send(Data data, Address address, A a, B b, C c) { ... }

Send(Data data, Address address, A a, D d, E e, F f) { ... }

Send(Data data, Address address, B b, H h, J j) { ... }

Where A, B, C, ... are types of values used for configuration. You're implicitly working with a Configuration type that can come in a finite set of "shapes" or combinations. You want a tagged union, but C# doesn't support them directly. However, you can implement one with inheritance. The key is to recognize that you can create an abstract class that has a finite set of subclasses by:

Giving the abstract class a private constructor.

Making the subclasses inner sealed classes of the abstract class.

The inner subclasses have access to the abstract class's private constructor, but top-level classes don't, so no one can add a new subclass "from the outside".

So you'd have something like this:

abstract class Configuration {
    private Configuration() {
        // Prevent outside subclassing
    }

    public sealed class Conf1 : Configuration {
         public A a { get; set; }
         public B b { get; set; }
         public C c { get; set; }

         // Constructor boilerplate
    }

    public sealed class Conf2 : Configuration {
         // Different fields
         // Constructor boilerplate
    }

    // ... more subclasses
}

(I don't work with C# regularly; hopefully I haven't made any serious syntax mistakes.)

Then all you need is a safe way to examine which kind of Configuration subclass you got. This is essentially the visitor pattern, but you can make it more concise with delegates:

abstract class Configuration {
    ...
    public abstract R Match<R>(Func<Conf1, R> ifConf1, Func<Conf2, R> ifConf2, ...);
    ...
    public sealed class Conf1 : Configuration {
        ...
        public override R Match<R>(...) {
            // Each subclass calls the delegate corresponding to it
            return ifConf1(this);
        }
        ...
    }

    // And so on with every other subclass
 }

Now you can reduce your Send to:

Send(Data data, Address address, Configuration config) {
    return config.Match(
        ifConf1: conf1 => { ... },
        ifConf2: conf2 => { ... },
        ...
    );
}

This all assumes that the number of combinations of configuration values is limited and doesn't change terribly often. I've assumed that, for example, all the Send methods use the same underlying mechanism and that it can simply be configured in a variety of ways. If you wanted to abstract over different kinds of sending services (e.g. e-mail vs some sort of IPC vs SOAP) then I'd use an interface similar to MainMa's Sender class since that solution always allows you to add new kinds of "senders" easily.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
As others have said, the developers should not be purposefully adding bugs in the software, but it is a legitimate strategy for your test suite to add bugs into the software as part of the testing process.

It's called mutation testing. The idea is to use software to automate the creation of small changes in the source code (called mutants). The changes are designed to create different behavior, for example, we could change

```<code>if x < 10:
    print "X is small!"
</code>```

into

```<code># we flipped the inequality operator
if x > 10:
    print "X is small!"
</code>```

and a good unit test should detect that the mutant code fragment no longer works as expected and kills the mutant. When the original code passes the test, and all mutants (that don't happen to be functionally equivalent) fail the test, then you know that your code and your tests are strong.

Body:
As others have said, the developers should not be purposefully adding bugs in the software, but it is a legitimate strategy for your test suite to add bugs into the software as part of the testing process.

It's called mutation testing. The idea is to use software to automate the creation of small changes in the source code (called mutants). The changes are designed to create different behavior, for example, we could change

if x < 10:
    print "X is small!"

into

# we flipped the inequality operator
if x > 10:
    print "X is small!"

and a good unit test should detect that the mutant code fragment no longer works as expected and kills the mutant. When the original code passes the test, and all mutants (that don't happen to be functionally equivalent) fail the test, then you know that your code and your tests are strong.


问:
Are there any benefits of using this extra variable in the for loop annotation?
I have found the following loop annotation in a big project I am working on (pseudocode):

```<code>var someOtherArray = [];
for (var i = 0, n = array.length; i < n; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

What brought my attention is this extra "n" variable. I have never seen a for lop written in this way before.

Obviously in this scenario there is no reason why this code couldn't be written in the following way (which I'm very much used to):

```<code>var someOtherArray = [];
for (var i = 0; i < array.length; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

But it got me thinking.

Is there a scenario when writing such a for loop would make sense? The idea comes to mind that "array" length may change during the for loop execution, but we don't want to loop further than the original size, but I can't imagine such a scenario.

Shrinking the array inside the loop does not make much sense either, because we are likely to get OutOfBoundsException.

Is there a known design pattern where this annotation is useful?

Edit
As noted by @Jerry101 the reason is performance.
Here is a link to the performance test I have created: http://jsperf.com/ninforloop. In my opinion difference is not big enough unless you are iterating though a very huge array. The code I copied it from only had up to 20 elements, so I think readability in this case outweighs the performance consideration.

答:
The idea comes to mind that "array" length may change during the for
  loop execution, but we don't want to loop further than the original
  size, but I can't imagine such a scenario.

The people talking about performance are probably correct that this is why it was written that way (the person who wrote it that way might not be correct that it significantly affects performance, but that's another matter).

However, to answer this part of your question, I think it's most likely to happen when the loop's main purpose is to modify the array it's looping over. Consider something like this, in pseudo-code:

```<code>guests = [];
for (i = 0; i < invitations.length; ++i) {
    if (! invitations[i].is_declined()) {
        guests.append(invitations[i].recipient())
    }
}
// maybe some other stuff to modify the guestlist
for (i = 0, n = guests.length; i < n; ++i) {
    if (guests[i].has_plus_one()) {
        guests.append(guests[i].get_plus_one());
    }
}
</code>```

Of course there's other ways to write it. In this case I could have checked for plus ones at the same time as checking whether the recipients accepted their invitations, and produced the full guest list one invitation at a time. I don't necessarily want to combine those two operations, but I can't immediately think of a reason why that's definitely wrong and therefore this design is required. It's an option to consider, occasionally.

Actually I think the thing that's most wrong with this code is that membership of the guests array means different things at different points in the code. Therefore I certainly wouldn't call it a "pattern", but I don't know that it's enough of a defect to rule out ever doing anything of this kind :-)

Body:
The idea comes to mind that "array" length may change during the for
  loop execution, but we don't want to loop further than the original
  size, but I can't imagine such a scenario.

The people talking about performance are probably correct that this is why it was written that way (the person who wrote it that way might not be correct that it significantly affects performance, but that's another matter).

However, to answer this part of your question, I think it's most likely to happen when the loop's main purpose is to modify the array it's looping over. Consider something like this, in pseudo-code:

guests = [];
for (i = 0; i < invitations.length; ++i) {
    if (! invitations[i].is_declined()) {
        guests.append(invitations[i].recipient())
    }
}
// maybe some other stuff to modify the guestlist
for (i = 0, n = guests.length; i < n; ++i) {
    if (guests[i].has_plus_one()) {
        guests.append(guests[i].get_plus_one());
    }
}

Of course there's other ways to write it. In this case I could have checked for plus ones at the same time as checking whether the recipients accepted their invitations, and produced the full guest list one invitation at a time. I don't necessarily want to combine those two operations, but I can't immediately think of a reason why that's definitely wrong and therefore this design is required. It's an option to consider, occasionally.

Actually I think the thing that's most wrong with this code is that membership of the guests array means different things at different points in the code. Therefore I certainly wouldn't call it a "pattern", but I don't know that it's enough of a defect to rule out ever doing anything of this kind :-)


问:
Git, semantic versioning and how it fits into (my) a typical development timeline?
I'm working on a Q&A system and about to tag my current application with "1.0.0" for it's first official version/tag. It's about to be rolled out for beta testing to a limited test audience next. Is "1.0.0" correct at this stage?

Also, no doubt there will be many bugs found at that stage. Do I keep it as "1.0.0" but forcefully moving the tag until it's release. Or upon fixing the bugs, would I give it a new tag "1.0.1". Then after another round of testing perhaps "1.0.2"

So when working on enhancements (e.g. new features such as a new menu, new search input field) would these be minor changes as in from "1.0.0" to "1.1.0"?

答:
You mention that you are looking at using semantic versioning, so lets look at the semantic versioning spec at http://semver.org/:

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,

MINOR version when you add functionality in a backwards-compatible manner, and

PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

and a little further down:

A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes. Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. Examples: 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92.

So if you a releasing a true beta of your 1.0 release, you should tag it 1.0.0-beta (or similar according to the spec). If you are going to have multiple beta releases as you fix bugs, then 1.0.0-beta.1, 1.0.0-beta.2, etc.

When you are adding features that are backwards-compatible, you should increment the MINOR number. If you make lots of internal changes that would cause breaking changes elsewhere in your application, then that is a MAJOR change. If you are making less dramatic changes (for example, you only add code and don't change behavior of existing code), then this would be a MINOR change. If you have a UI heavy application and completely change that UI, I would also say that is a MAJOR change as well (UI can be considered the API for end users).

As for how to add indicators to your git repo, I'd suggest that you first create a 1.x branch. This will allow you to easily follow everything in version 1 while allowing continued development of version 2 on master. Then you tag the beta release with a tag 1.0.0-beta (or -beta.1 if there will be multiple betas). Once you fix all the bugs you need to fix, tag the actual 1.0.0 release. Then tag each release as necessary.

You can take a look at some tried-and-true workflows for git like git flow and github flow for ideas of how you want to set up your ongoing workflow.

Also, if you want a little more context about semantic versioning for programs without an API, this answer goes into some depth.


问:
MVC: How dumb should the view be?
creating an MVC structure and pondering this...

My view has an Add button. Click it and we send off a request to the controller (using pub/sub so view doesn't really know who its talking to). Having done this the view disables its Add button until it receives a "data added" event from the controller (again pub/sub so doesn't really know who from). At this points it updates its list and re-enables the add button.

My question is this. Should the view contain this logic about enabling/disabling the add button or should the controller? My thoughts so far are perhaps the controller because it is up to the controller whether multiple adds can be handled at any one time or whether they need to be serialised in the method described. however, it is easier to implement the current scheme in the view as don't have to expose so many methods to control the view.

Is there a preferred way that is the most MVC compliant? Thanks :)

答:
The Controller should be just as dumb as the View.

So in this case, we need to ask about responsibility.

Views are responsible for UI elements and displaying things.  Controllers are responsible for connecting Views with Models and providing data for the View to display.

A Controller should be dumb about what the View has within it, buttons included.  So the View should be responsible for enabling / disabling the button.

Keeping the Controller oblivious of the View allows you to more easily decouple the View from the Controller and have multiple types of Views reuse the same Controller.

Title: MVC: How dumb should the view be?


答: In all likelihood, you should be doing this so that the add button doesn't get enabled again until there is something to add.  That means you need client-side validation, which occurs in the View.</p>

Title: MVC: How dumb should the view be?

Body:
creating an MVC structure and pondering this...

My view has an Add button. Click it and we send off a request to the controller (using pub/sub so view doesn't really know who its talking to). Having done this the view disables its Add button until it receives a "data added" event from the controller (again pub/sub so doesn't really know who from). At this points it updates its list and re-enables the add button.

My question is this. Should the view contain this logic about enabling/disabling the add button or should the controller? My thoughts so far are perhaps the controller because it is up to the controller whether multiple adds can be handled at any one time or whether they need to be serialised in the method described. however, it is easier to implement the current scheme in the view as don't have to expose so many methods to control the view.

Is there a preferred way that is the most MVC compliant? Thanks :)


问:
Is it ok for a for a View to dismiss itself?
Currently, I'm working on a project in which a view is dismissing itself.

While talking to another programmer on the team for this project, he said that it's fine (in that it behaves correctly), but that I really should be using a delegation pattern to dismiss a view.

I've been programming in Objective-C for awhile now, but am still trying to fully understand design patterns, such as delegation. Is it acceptable for a view to dismiss itself, or should I in-fact be using delegation? When is delegation not an acceptable design pattern for use?

答:
Delegation in code is the same thing as it is in real life; you're handing a task off to someone or something else to execute.  In user interfaces that have event handling, this is a good thing, as the code behind the UI is already complex enough, and delegation helps avoid a big ball of mud.  As a matter of general practice, I push as much logic as I can to external code, rather than keeping it in the UI.

That said, having a form close/dismiss itself is not exactly rocket science, and doing so encapsulates the functionality of closing within the form itself, rather than having to involve another object just to close the form.  That's extra complexity for no additional benefit, especially if that's the only thing you're delegating to the external object.

So I'd say if the form is closing due to some interaction in or on the form (say, the user clicking a close button, or a timer in the form), then just close it in the form's code, and be done with it.  If the form is closing due to some external action, then let that external action close it.


问:
What methods are there to avoid a stack overflow in a recursive algorithm?
Question

What are the possible ways to solve a stack overflow caused by an recursive algorithm?

Example

I'm trying to solve Project Euler problem 14 and decided to try it with a recursive algorithm. However, the program stops with a java.lang.StackOverflowError. Understandably. The algorithm indeed overflowed the stack because I tried to generate a Collatz sequence for a very large number.

Solutions

So I was wondering: what standard ways are there to solve a stack overflow assuming your recursive algorithm was written correctly and would always end up  overflowing the stack? Two concepts that came to mind were:

tail recursion

iteration

Are ideas (1) and (2) correct? Are there other options?

Edit

It would help to see some code, preferably in Java, C#, Groovy or Scala.

Perhaps don't use the Project Euler problem mentioned above so it won't get spoiled for others, but take some other algorithm. Factorial maybe, or something similar.

答:
As for Scala, you can add the @tailrec annotation to a recursive method. This way the compiler ensures that tail call optimization actually took place:

So this won't compile (factorial):

@tailrec
def fak1(n: Int): Int = {
  n match {
    case 0 => 1
    case _ => n * fak1(n - 1)
  }
}
```

<p>the error message is:</p>

<blockquote>
  <p>scala: could not optimize @tailrec annotated method fak1: it contains a recursive call not in tail position</p>
</blockquote>

<p>On the other hand:</p>

<pre class="lang-scala prettyprint-override"><code>def fak3(n: Int): Int = {
  @tailrec
  def fak3(n: Int, result: Int): Int = {
    n match {
      case 0 => result
      case _ => fak3(n - 1, n * result)
    }
  }

  fak3(n, 1)
}
</code>```

compiles, and tail call optimization took place.

Body:
As for Scala, you can add the @tailrec annotation to a recursive method. This way the compiler ensures that tail call optimization actually took place:

So this won't compile (factorial):

@tailrec
def fak1(n: Int): Int = {
  n match {
    case 0 => 1
    case _ => n * fak1(n - 1)
  }
}

the error message is:

scala: could not optimize @tailrec annotated method fak1: it contains a recursive call not in tail position

On the other hand:

def fak3(n: Int): Int = {
  @tailrec
  def fak3(n: Int, result: Int): Int = {
    n match {
      case 0 => result
      case _ => fak3(n - 1, n * result)
    }
  }

  fak3(n, 1)
}

compiles, and tail call optimization took place.


问:
Why are FLOSS licences applied to files instead of diffs/deltas?
In the case of open source software development, where contributions build on previous work I would find it more sensible for each copyright holder to hold copyrights on the diffs/deltas he/she contributed, instead of copyrights on files.
Unless a contributor created a file, the contribution is a modification.

AFAIK, in projects with no CLAs, like the Linux kernel, copyright for contributions from different sources is still handled on a per file basis.

Implementing this concept means licensing would have to be integrated into Git/Mercurial/Bazar/Fossil/SVN, and at first it would be more complicated than adding a commented header with the license to each file.

What are the reasons (legal, technical, political, customary or otherwise) software licenses are applied to files instead of to diffs/deltas, especially now that version control systems are in wide spread use? Or is this a novel idea?

Note 1: Obviously the question does not apply in cases where there are Contributors Licence Agreements, and does not apply to non-FLOS Software.

Note 2: I mistakenly asked this on Stackoverflow and since instead of being moved here it was closed, I am asking this question here.

Note 3: A diff can be any of the following and more: a change to a single file, changes to multiple files, new files, any combination of the previous.

Note 4: The proposal mainly targets 2 situations:

Discouraging creation of copylefted forks of copyfree projects for the sole reason of copylefting, accomplished by maintaining both copyleft and copyfree contributions in the same source tree, and filtering based on license.

Enable license switching with the approval of all people necessary without anyone extra (e.g.: What if Linus would change his mind and would want to switch the license for Linux from GPLv2 to GPLv2+. Who would he have to track down and ask permission from. Must he ask permission from those whose contributions were discarded?)

答:
Probably because the end users are using your files, not your diffs, and licenses are supposed to be distributed along with your software (whether in source or binary or some other form). You don't distribute your software as a series of annotated diffs, do you?

There may also be a legal reason, but that's a question for a different website.


答:
I think you are confusing licensing and copyright. Each contributor to a shared project without copyright assignment only owns the copyright over their own contributions, in other words copyright over each diff they produce. A contributor would only own the copyright over a whole file if nobody else contributed to that file. As a result, most files have shared copyright between multiple authors.

Now why do we need licenses?
If a software is meant to be used by other people, it requires a license: the license states the terms under which other people may use the software. For example, you are not generally allowed to modify some software and publish your modifications. Even if you have access to the source of some software, you may not publish any enhancements you wrote. If we have a project where we want people to contribute, the whole project needs to be available under a license that allows this. And all contributions must also be provided under this license so that others may build upon these contributions as well.

It is not viable to have one project or one file contain code under multiple different licenses. For starters, many licenses assume they are applied on a per-file or per-project basis. Also, imagine a potential user or contributor trying to figure out whether they can use the software. It is not realistic to look through all previous contributions to check whether they can use, modify, and distribute a software. It is much simpler to state one project-wide license, and any contributions must also be provided under that license.

Title: Why are FLOSS licences applied to files instead of diffs/deltas?

Body:
In the case of open source software development, where contributions build on previous work I would find it more sensible for each copyright holder to hold copyrights on the diffs/deltas he/she contributed, instead of copyrights on files.
Unless a contributor created a file, the contribution is a modification.

AFAIK, in projects with no CLAs, like the Linux kernel, copyright for contributions from different sources is still handled on a per file basis.

Implementing this concept means licensing would have to be integrated into Git/Mercurial/Bazar/Fossil/SVN, and at first it would be more complicated than adding a commented header with the license to each file.

What are the reasons (legal, technical, political, customary or otherwise) software licenses are applied to files instead of to diffs/deltas, especially now that version control systems are in wide spread use? Or is this a novel idea?

Note 1: Obviously the question does not apply in cases where there are Contributors Licence Agreements, and does not apply to non-FLOS Software.

Note 2: I mistakenly asked this on Stackoverflow and since instead of being moved here it was closed, I am asking this question here.

Note 3: A diff can be any of the following and more: a change to a single file, changes to multiple files, new files, any combination of the previous.

Note 4: The proposal mainly targets 2 situations:

Discouraging creation of copylefted forks of copyfree projects for the sole reason of copylefting, accomplished by maintaining both copyleft and copyfree contributions in the same source tree, and filtering based on license.

Enable license switching with the approval of all people necessary without anyone extra (e.g.: What if Linus would change his mind and would want to switch the license for Linux from GPLv2 to GPLv2+. Who would he have to track down and ask permission from. Must he ask permission from those whose contributions were discarded?)


答: It's because the modifications are legally considered a derivative work, because they build on and depend on the work already done.  This protects the original authors against someone adding a popular new feature that builds on their work, but then making that feature closed source.  If authors wish to allow closed-source extensions to their software, they can make that explicit, such as how the linux kernel allows closed source modules, but requires them to be marked as "tainted."


问:
Is this the template method pattern?
Could someone tell me whether the following is A) a good solution to the problem of repeating code and B) an example of the template method?

Let's say I have one table, named VEHICLES, which I use to store different types of vehicles (e.g. car, van, bus). I have a bunch of repository classes which should retrieve each type of vehicle:

```<code>class CarRepository{
  public function getAll(){
    $sql = "select * from vehicles where type='car'";
    //some code to communicate with the database
  }
}

class BusRepository{
  public function getAll(){
    $sql = "select * from vehicles where type='bus'";
    //some code to communicate with the database
  }
}
</code>```

As you can see, each repo has almost the same code in the getAll method, which isn't very DRY. I was thinking a better solution might be to have a common base class for the repos, like this:

```<code>abstract class VehicleRepository{
  final public function getAll(){
    $sql = "select * from vehicles where type='".$this->getType()."'";
    echo $sql;
    //code to communicate with the database
  }

  abstract function getType();
}
</code>```

And then each repo would just need to define the getType method:

```<code>class CarRepository extends VehicleRepository{
    public function getType(){
        return "car";
    }
}

class BusRepository extends VehicleRepository{
    public function getType(){
        return "bus";
    }
}
</code>```

Does this seem reasonable? And is this what is meant by the template method pattern?

答:
Yes, that is the template method pattern

Currently there is no need to make the getType methods public, "protected" would be enough. If you actually need them outside of that class hierarchy, you can make them public, of course.

Title: Is this the template method pattern?


问:
When passing dates/datetimes as url parameters in an API, which format is better - unix timestamp or date string (ISO 8601)
Interesting question came up at work in regards to the better format of passing a date/datetime as a url parameter in an API: Is it better to pass as a unix timestamp, or as a plaintext date string (01/30/2015 04:17:57pm, 2015-01-27T16:17:57+00:00)?

答:
It depends on the usage, but I'd probably say it's safest to convert to UTC then pass the ISO 8601 style string as you suggest.

That way, it's human-readable, and you don't have to worry about different time zones, etc.

While I was researching for an answer, I found an interesting answer on StackOverflow you might want to read: link.

(edit) Also, if you're using ISO 8601, there's no doubt about the interpretation of the format (DD/MM/YYYY vs. MM/DD/YYYY vs. YYYY/DD/MM vs. YYYY/MM/DD etc.).


问:
Using "Return" over "Break" or a combination
When using the Switch statement, is using return instead of break or a combination of the two considered bad form?

```<code>while (true)
{
    var operation = Randomness.Next(0, 3);
    switch (operation)
    {
        case 0:
            return result + number;
        case 1:
            if ((result - number) > 0)
            {
                return result - number;
            }
            break;
        case 2:
            return result * number;
        case 3:
            if ((result % number) == 0)
            {
                return result / number;
            }
            break;
    }
}
</code>```

答:
I'd avoid using multiple return statements in a method like that for the simple reason that you'd need to put a breakpoint on every return statement to see which value is returned (and why).

It'd be better to do something like

```<code>while (true)
{
    var operation = Randomness.Next(0, 3);
    double? valueToReturn = null;

    switch (operation)
    {
        case 0:
            valueToReturn = result + number;
            break;
        case 1:
            if ((result - number) > 0)
                valueToReturn = result - number;
            break;
        case 2:
            valueToReturn = result * number;
            break;
        case 3:
            if ((result % number) == 0)
                valueToReturn = result / number;
            break;
    }

    if ( valueToReturn.HasValue )
        return valueToReturn.Value;
}
</code>```

For a discussion on having multiple return statements in a function, see this StackOverflow question.

Body:
I'd avoid using multiple return statements in a method like that for the simple reason that you'd need to put a breakpoint on every return statement to see which value is returned (and why).

It'd be better to do something like

while (true)
{
    var operation = Randomness.Next(0, 3);
    double? valueToReturn = null;

    switch (operation)
    {
        case 0:
            valueToReturn = result + number;
            break;
        case 1:
            if ((result - number) > 0)
                valueToReturn = result - number;
            break;
        case 2:
            valueToReturn = result * number;
            break;
        case 3:
            if ((result % number) == 0)
                valueToReturn = result / number;
            break;
    }

    if ( valueToReturn.HasValue )
        return valueToReturn.Value;
}

For a discussion on having multiple return statements in a function, see this StackOverflow question.


问:
Scheduling a few CPU-intensive tasks
I need to schedule a small number of CPU-intensive tasks to run every so often, reading from shared data and writing to dedicated buffers. I don't necessarily want to roll my own scheduling, but am unsure if libraries like Quartz are appropriate for this small of scale. I'm using Java 8 in a server environment, but with isolated nodes and it doesn't matter if a few iterations are lost every now and then.

Problem detail:

I have 5 buffers of data of binary data to process. Before processing each buffer, I allocate an empty destination and the function writes to that destination. Each buffer needs to be processed on a different schedule with a different function, although all the functions can handle missing an iteration and calculating double on the next go.

The first buffer is ~30mb and takes ~200ms to process, and needs to be processed every 500ms. The remainder are around ~6mb each and take ~50ms to process, and need to be processed every 1000ms.

The processing functions must only write to the destination buffer and are stateless, but may read any of the existing buffers. The whole process will at least have its own thread, and may have multiple threads. None of this is critical, it won't be clustered, and will be maintained almost exclusively in-memory.

Example:

A fairly dumb implementation might be:

```<code>for (layer in parent.layers) {
    new thread(() => {
        while (true) {
            buffer = new int[layer.data.length]
            process(layer.data, buffer, parent)    // remember, this can access other layers
            layer.data = buffer
            sleep(layer.increment)
        }
    }
}
</code>```

Running each layer on its own thread makes the processing fairly simple, so long as nothing in the middle is locked. Grabbing each layer the processing function cares about when it begins an iteration and releasing them at the end should work, since they are read-only and I'm not worried about another thread replacing the reference.

Question:

Are there any issues with Timers for this kind of work? Do they provide a way to discard or wait on the previous iteration?

Is Quartz a viable choice, or simply absurd?

Can something as simple as System.nanoTime suffice at this precision?

答:
Using a single Timer and an unbounded ExecutorService (thread pooling) for this type of general-purpose scheduling can be very powerful.  However, it does not stop concurrent execution of the task, should the previous invocation not yet be completed.

We've combined Timer and ExecutorService just for this purpose, along with the ability to restrict the number of concurrent tasks based on the number of CPUs available to the system (appropriate for CPU-bound tasks):

http://www.aoindustries.com/docs/ao-concurrent/com/aoindustries/util/concurrent/ExecutorService.html

To stop concurrent invocation with only these two tools you'd have to roll your own protection.

I solved this problem recently by creating a "ConcurrencyLimiter" that will serialize access to an arbitrary piece of code/resource given an arbitrary key object.  If a second thread tries perform the same task, it'll simply wait and use the result from the first thread.  Thus, concurrency is avoided and both threads get a meaningful response.

http://www.aoindustries.com/docs/ao-concurrent/com/aoindustries/util/concurrent/ConcurrencyLimiter.html

Regarding limiting concurrency within the task scheduler itself, there is also a simple pure-Java implementation of cron that allows to avoid concurrent execution and handles all of the scheduling:

http://www.aoindustries.com/docs/ao-cron/com/aoindustries/cron/CronDaemon.html

Source at http://www.aoindustries.com/src/ao-concurrent.src.jar (depends on http://www.aoindustries.com/src/aocode-public.src.jar) and http://www.aoindustries.com/src/ao-cron.src.jar  All LGPLv3 and free for the world, no external dependencies, and Java 1.6+.

The point here isn't to plug my own code.  I just want to point-out that you can either handle it at the scheduling level or within the task itself.

Sorry - vague questions get vague answers.

Title: Scheduling a few CPU-intensive tasks


问:
Test & remove, or always remove
I have a function to show or hide a certain UI control. In my example case below, the framework is jQuery I'm using for an event to show a tool tip that may fire a LOT (based on mouse movements) - but the underlying problem is more general and may also arise in a similar manner in lots of other UI frameworks. In fact, the problem could be even more generalized to any kind of component with two states to be switched often, not just UI components.

Consider:

Code A:

```<code>$(this).plothover(function(item) {
   if(item&&item!="undefined"){
      show tooltip
   }
   else
     remove tooltip
});
</code>```

Code B:

```<code>$(this).plothover(function(item) {
   if(item&&item!="undefined"){
      show tooltip
   }
   else {
      if(tool tip is shown){
           remove tooltip
      }
   }
});
</code>```

item will exist at defined Cartesian points where datapoints exist (ie, graph coordinates on a canvas).  In other words, the odds are ~10000:1 in the favor of the else condition firing on a DPI basis.

As the mouse moves,

Code A removes it with no regard to any condition
Code B only removes it if it was already created, but has to test the creation first

So, which is considered 'right'?
Blind hide the control whether it is visible or not, or only hide it if it is visible?

I've benchmark'ed it through jsperf and the differences are negligible performance wise but does lean towards the blind destroy.  But if it's 'wrong' by theory to do it, i'd rather chose the best practice route.

--- EDIT ---
To clarify, The actual invocation is not important (ie, how is it removed). Nor am I looking for a code review. The above given example is one of many times I've run into this case.

Rather, I wish to discuss the theory involved in "Destroy what may exist" or "search and destroy if it exists".

答:
Here's my post from Code Review I posted before the question got closed there:

Why test in the first place? When you are trying to avoid an expensive operation, one that is significantly more expensive than the test itself.

Your performance gain comes from selectively calling remove and gaining the time not spent always removing it.

So your answer is, given 2 actions, test and remove, and p the probability of the tooltip being shown, test and remove when time(remove) > time(test) + p * time(remove).

Which is exactly why how it's being removed matters.

Title: Test & remove, or always remove


答:
As others have already said, it's not the job of QA to solely find bugs. I would go further and say it's not their job at all, technically. Developers should be responsible for keeping their own code bug-free. Test suites should be run before new code is ever even committed, and if the test-suites fail, then it should never be making it to QA in the first place. Introducing bugs intentionally means you definitely can't pass your test suites, so why is your code going to QA?

The job of QA is to validate the application against the user stories it implements. They should test the flow, the UI, etc. and ensure that the user can do everything the user should be able to do, in the most usable and accessible way as possible. While doing this, of course, they may stumble upon bugs, but that's a side-effect of what they do, not what they do. Remember QA means Quality Assurance, not Bug-free Assurance.

Title: Leaving intentional bugs in code for testers to find

Body:
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).


问:
Use JSON objects or POJOs in back end service?
I'm building a back end service for mobile clients.

The requirement is that the mobile clients will pass me a token, I'll use that token to talk to other systems (behind the company firewall) in my company, and return to the user some information.

Here's a typical scenario:

A mobile client asks for some customer data and makes a call with the customers token. I use the token against the customer database system and get back the customer details. I then return the data (removing some fields that are not relevent )to the mobile client.

All data between systems (me, mobile client, customer database) use JSon.

The question is whether I should work with JSon objects throught my code or try and use POJOs?

Right now, I only need to remove some fields from the customer database before returning to the client.

The future may require more involved transformations but I can't be sure that will happen or the nature of the transformations.

Thanks

答:
It's usually a good idea to separate the serialization method (JSON) from your business logic so that if in the future you decide to use some other type of serialization, you can do so without affecting the business logic.

Jackson is probably the most popular open-source library for JSON serialization/deserialization in Java.

In the situation where some amount of transformation is needed between the data received from your customer database and what you actually return to the caller, I usually create a separate DTO (data-transfer object) class that contains only the fields to be serialized.

On the other hand, if you always need to remove the same fields from the customer data before transmittal and don't mind putting serialization-specific annotations on your POJOs, you can use Jackson's @JsonIgnore (or similar) on those fields and skip the DTO.


问:
Making a sequence strictly increasing by joining neighboring numbers using the smallest number of moves
I've got a following problem to solve:

```<code>You are given a list of positive integers [x_1;x_2;...;x_n]. You are allowed to
change 2 integers standing next to each other to one equal to their sum. (So for
example in list [x_1;...;x_3;x_4;x_5;x_6;...;x_n] you pick x_4 and x_5 and the new list
becomes [x_1;...;x_3;(x_4+x_5);x_6;...;x_n]). Find the minimum number of such changes
needed to get a list in which integers are in strictly increasing order.
</code>```

How to approach such a problem? Intuitively it looks like Dynamic Programming problem (something like multiplying matrices) but I cannot find any connected subproblems. Any idea how to solve this using something else than brute-force?

答: If you are allowed to combine multiple times, just sum all the numbers into a single value.  A list of one number is sorted :)  So the number of moves is n-1.</p>


问:
How to implement the repository pattern for an app that will change its database from sql to nosql on in couple of years?
I have been reading a lot about repository implementation. I am confused about which way to implement it for a project I am sure would change its data layer methods because of db migration from MS Sql Server to NoSQL in a couple of years.

Imp #1

Implement Rep layer as a completely separate layer. This will have
its own interface and conversion methods here. This rep layer has a
dependency on DAL and in turn BLL will have a dependency on this
layer

Imp#2

Implement Repository not as a separate layer but have its interfaces
in Business Logic Layer and the methods in DAL.

I am leaning more towards imp #1 since it looks cleaner. However some explanations of experts I have read use imp#2. I think there must be a clear reason to use one over another according to the situation. I would ideally want our switch to a different database be as painless as possible.

答:
@JDT's answer is correct. Imp#2 is the better option. The dependency inversion principle (DIP) as described by Robert C. Martin implicitly demands that if you have two modules A and Band an interface IB which is implemented by B and injected into A the definition of IB should be within the context of A.

Actually it's the second clause of the DIP that demands this:

Abstractions should not depend on details. Details should depend on
  abstractions.

In the case of BLL and DAL the BLL is the high level module und the DAL is the low level module. If the abstraction (the interfaces for the repositories e.g.) would be definied within the DAL then the abstraction (the interfaces) would depend on the details (the implementation). If the details change (e.g. when you swith to the NoSQL DB implementation) the abstraction/interfaces will also change and the high level module (the BLL) will have to be changed as well. And this is not desired. So clearly the answer to your question is Option #2.

Looking briefly for some sources to back this up I found this on Wikipedia on the DIP:

The interfaces defining the behavior/services required by the
  high-level component are owned by, and exist within the high-level
  component's library. The implementation of the high-level component's
  interface by the low level component requires that the low-level
  component package depend upon the high-level component for
  compilation, thus inverting the conventional dependency relationship.


问:
Java logging dependency for a low-level library
I inherited a lower-level open source Java network library.  The library is intended to be used by higher-level application protocol libraries which are in turn used by application code.  My library, as left by the previous maintainer, has no dependencies and is built via Ant.  The build artifact is a simple jar that others can drop into their projects.

I am in the process of converting the library to be built with Maven.  As I'm doing this, I'm considering possibly adding slf4j as a dependency.  Currently, when something goes wrong, stack traces or other information is spit out to System.out or System.err.  I know that that's not always very helpful, but these outputs only happen at 10 to 15 places in the code and are rarely executed.

So what do you think?  Keep the library simple with zero dependencies or introduce slf4j?

答:
Coding to the SLF4J API doesn't force the dependency on users of your library. From the user's guide:

As of SLF4J version 1.6.0, if no binding is found on the class path, then slf4j-api will default to a no-operation implementation discarding all log requests.

...

Embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api. When a library declares a transitive dependency on a specific binding, that binding is imposed on the end-user negating the purpose of SLF4J. Note that declaring a non-transitive dependency on a binding, for example for testing, does not affect the end-user.


答:
I would use an A* search algorithm. A* is a best-first search using always the node with the lowest total cost g(l)+h(l), where g is the "past path cost function" and h is the "future path-cost function". The search space is a graph where each node is one of the possible lists you can reach by subsequent adding of two numbers, starting with your initial list. The edges of the graph are defined by the moves. The past path-cost function g(l) is given by the number of moves so far to reach the list l. The future path-cost function h(l) is given by the number of pairs (x_i,x_(i+1)) in the list l where x_(i+1) is less or equal to x_i. For example, when h(l)=0, the list l is strictly increasing and you reached an end node in your graph.

Note that each move can reduce the number of such pairs by one at maximum, so h will be never an overestimation, which guarantees the A* search will find the optimal solution.

For this kind of problem, it will certainly make sense to avoid having the same list l analysed twice, since the same list can be reached by different sequences of summation. So during the search, store every list (=graph node visited) in a hash set and prune the search when reaching the same list again.

Title: Making a sequence strictly increasing by joining neighboring numbers using the smallest number of moves

Body:
I've got a following problem to solve:

```<code>You are given a list of positive integers [x_1;x_2;...;x_n]. You are allowed to
change 2 integers standing next to each other to one equal to their sum. (So for
example in list [x_1;...;x_3;x_4;x_5;x_6;...;x_n] you pick x_4 and x_5 and the new list
becomes [x_1;...;x_3;(x_4+x_5);x_6;...;x_n]). Find the minimum number of such changes
needed to get a list in which integers are in strictly increasing order.
</code>```

How to approach such a problem? Intuitively it looks like Dynamic Programming problem (something like multiplying matrices) but I cannot find any connected subproblems. Any idea how to solve this using something else than brute-force?


答:
If you use the Maven Assembly Plugin, you can include the slf4j jar (along with whichever implementation you prefer) inside your deployed jar. There are more complicated options if you want to allow users to choose the logging library, but it will run perfectly well if you make a fat jar with or without the slf4j implementation.

Users are much more likely to be annoyed - unless hard drive space is really (and I mean really) at a premium - if they have to deal with System.out and System.err output than if there's a provided logging framework, even if it's just the default no-op implementation and the have to add log4j or logback if they want to see the logs.

Title: Java logging dependency for a low-level library

Body:
I inherited a lower-level open source Java network library.  The library is intended to be used by higher-level application protocol libraries which are in turn used by application code.  My library, as left by the previous maintainer, has no dependencies and is built via Ant.  The build artifact is a simple jar that others can drop into their projects.

I am in the process of converting the library to be built with Maven.  As I'm doing this, I'm considering possibly adding slf4j as a dependency.  Currently, when something goes wrong, stack traces or other information is spit out to System.out or System.err.  I know that that's not always very helpful, but these outputs only happen at 10 to 15 places in the code and are rarely executed.

So what do you think?  Keep the library simple with zero dependencies or introduce slf4j?


问:
Should Latin-1 be used over UTF-8 when it comes to database configuration?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.

When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.

My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).

The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?

Are there other reasons one should use Latin-1 over UTF-8? It's my understanding that it is superior and becoming more ubiquitous.

答:
Which of us is right?

Once upon a time, your boss was. But as time goes by, things change. Nowadays, you are (but before running to your boss, be sure to read Nelson's answer too).

Old versions of MySQL, and old versions of mostly everything, dealt much better with the older Latin1/ISO-8859-1(5) than UTF8.

There is a reason why UTF8 has been created, evolved, and pushed mostly everywhere: if properly implemented, it works much better. There are some performance and storage issues stemming from the fact that a Latin1 character is 8 bits, while a UTF8 character may be from 8 to 32 bits long. So when planning VARCHAR you need to take this into account. And your search routines will be a tad slower. They will be able to do more things (e.g. searches with accent sensitivity or without. Can't do those in Latin1 without extensive work), but they will take a bit more time.

But on the other hand, storage is cheap, the realistic overhead on file sizes is less than 2-3%, computing power is also cheap and getting cheaper in good accord with Moore's Law; while your time and your customers' expectations definitely aren't.

You might have to worry for search tools etc. if you were the one to develop such tools. But you probably aren't. You use those tools; even those that were not completely UTF8 compliant yesterday (as the earlier MySQLs weren't), are today, or soon will be (e.g. MySQL with utf8mb4 support).

So by carefully planning and implementing UTF8 the right way (not slapping it over Latin1 as an afterthought) you can have code that is very reasonably future-proof, which, if you plan on ever doing business with any Asiatic country, is a Very Good Thing. And if you have no such plans, other people will have, and those people could be your customers, suppliers, or partners.

So when they start sending you UTF8 data, you'll have to set up a complicated thingamajig to convert to and fro Latin1, and deal with unsolvable cases.

When you factor in the budget the cost of several skirmishes against the evil mojibake ninjas, and consider that they are not going to go away - as you already discovered - then you'll realize that going UTF8 is not only simpler, it's going to be cheaper as well.


答:
Unicode is certainly difficult, and the UTF-8 encoding has a couple of inconvenient properties. However, UTF-8 has become the de-facto standard encoding on the web, surpassing ASCII, Latin-1, UCS-2 and UTF-16. Just use UTF-8 everywhere.

The most important reason why you should support Unicode is that you shouldn't make unnecessary assumptions about user input. I have no idea what your domain is, but things like Hebrew usernames, a blog post about China, a comment with Emoji, or simply well styled text – like “this” – should be possible… Oh, those were typographically correct quotation marks (“” rather than ""), en-wide dashes, and an ellipsis, which are characters that are common in English text, but not supported by ASCII or Latin-1. So not supporting other scripts isn't just a big f*ck you to other cultures, but sticking to Latin-1 doesn't even allow you to write proper English.

The notion that Unicode only allows “bad characters” is wrong. Yes, text is really complicated, and Unicode won't hide that from you. Your boss may be thinking about composed characters, where one base codepoint such as a is modified by subsequent codepoints that e.g. represent diacritics to form one visual character such as á. This doesn't really get into your way when trying to do searches if you do some kind of normalization. For example, you could store all text in the NFC form which collapses such compositions into their precomposed form if one is available. When doing searching, you could also strip all composing characters from the text, but this may substantially change their meaning in some languages.

Unicode also adds a lot of unprintable characters – but even ASCII has loads of them. Will you handle a NUL in the middle of a string? How about 0x1C, a “File Separator”? I've never seen half of those. Latin-1 adds a soft hyphen that indicates word break opportunities, but is otherwise invisible. Does that also break your full-text search? In other words, even ASCII and Latin-1 allow you to completely break your input if you assume it's all just printable text!

Title: Should Latin-1 be used over UTF-8 when it comes to database configuration?

Body:
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.

When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.

My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).

The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?

Are there other reasons one should use Latin-1 over UTF-8? It's my understanding that it is superior and becoming more ubiquitous.


问:
Why can we use the same name for local variable in different scopes?
I was wondering why is it possible that we can use the same name for local variable in different scopes?

Like we can have two methods which both can have variable with the same name.

What makes this possible and what happens behind the scenes?

答:
Why can we use the same name for local variable in different scopes?

Each method has its own set of local variables.  The compiler converts these local variable names, in essence, to per-method unique numbers (stack frame offsets).  After compilation the names of local variables are lost (disregarding some of the newer reflection APIs).

Local variables only exist while the method is being executed and are reset each time the method is invoked.

What makes this possible and what happens behind the scenes?

Local variables are stored on the "stack".  Thus, each call to a method gets its own copy of local variables.  As the methods return the space allocated on the stack is released.

This stack is also the key reason that method calls can even be recursive, where a method calls itself.  Each call gets its space on the stack.

Further search for terms like "stack" and "local variable" may let you find more.


答:
When the compiler enters a "new scope", new variables within that scope are stored for that scope, and when the scope "disappears", those variables disappears. This is, normally, done in the form of some sort of stack/list type, which in turn holds the variable names and their type.

So, if we have:

```<code>int x;

void func()
{
   float x, y;
   int a;
}
</code>```

the stack will have level 0 with {x, int}, and level 1 with {x, double}, {y, double}, {a, int}.

I've written my own pascal compiler in C++ (using LLVM to do the actual code generation), and here's my "name-stack":

https://github.com/Leporacanthicus/lacsap/blob/master/stack.h

It uses the StackWrapper to keep track of the number of levels.

This should not be confused with the fact that a stack is used for nesting calls to functions, and storing the local variabls - that's a stack in the runtime environment, and whilst both conceptually are similar, the stack in the compiler is there to track different scopes, the one in the runtime keeps track of calls to functions, arguments to functions and local variables.

Title: Why can we use the same name for local variable in different scopes?

Body:
I was wondering why is it possible that we can use the same name for local variable in different scopes?

Like we can have two methods which both can have variable with the same name.

What makes this possible and what happens behind the scenes?

Body:
When the compiler enters a "new scope", new variables within that scope are stored for that scope, and when the scope "disappears", those variables disappears. This is, normally, done in the form of some sort of stack/list type, which in turn holds the variable names and their type.

So, if we have:

int x;

void func()
{
   float x, y;
   int a;
}

the stack will have level 0 with {x, int}, and level 1 with {x, double}, {y, double}, {a, int}.

I've written my own pascal compiler in C++ (using LLVM to do the actual code generation), and here's my "name-stack":

https://github.com/Leporacanthicus/lacsap/blob/master/stack.h

It uses the StackWrapper to keep track of the number of levels.

This should not be confused with the fact that a stack is used for nesting calls to functions, and storing the local variabls - that's a stack in the runtime environment, and whilst both conceptually are similar, the stack in the compiler is there to track different scopes, the one in the runtime keeps track of calls to functions, arguments to functions and local variables.


答:
I often prefer standard and good enough over best.  There could be a "less is more" argument for using the included Java Logging:

http://docs.oracle.com/javase/6/docs/technotes/guides/logging/overview.html


答:
Good answers already given, but I would also find a way to incorporate the git sha1 in your application, so you can find that it was git commit 1b5619273127398123 that was the one used in this particular release. That way, if Mr Smith from BigCo calls and complains that his app isn't working just right, you can ask "What is the long row of digits and letters on the second wor when you click About?", and git checkout NNNNNN to get exactly that version, then do the same steps as Mr Smith did, and (hopefully) reproduce the problem. There's nothing worse than trying to find a problem that you can't reproduce because you are using a subtly different version (where you by chance or on purpose avoid that particular issue).

Also make sure that your build system is included in the version - preferrably including which compiler version and so on - either encoded or store which build tools you use when you build the product inside your git repo.

Title: Git, semantic versioning and how it fits into (my) a typical development timeline?

Body:
I'm working on a Q&A system and about to tag my current application with "1.0.0" for it's first official version/tag. It's about to be rolled out for beta testing to a limited test audience next. Is "1.0.0" correct at this stage?

Also, no doubt there will be many bugs found at that stage. Do I keep it as "1.0.0" but forcefully moving the tag until it's release. Or upon fixing the bugs, would I give it a new tag "1.0.1". Then after another round of testing perhaps "1.0.2"

So when working on enhancements (e.g. new features such as a new menu, new search input field) would these be minor changes as in from "1.0.0" to "1.1.0"?


问:
How to earn team members respect as team lead
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>

答:
As a leader, you are given a job to be done and a set of people and resources to do it with, and your job is to coordinate things.

As "a complete neophyte," you're lacking the single most important attribute of a leader: knowledge of your team.  The first thing I would do in your situation is to talk to each member of the team and get to know them.  Learn their personalities, their strengths, (particularly their specialties,) and their weaknesses.

Once you've got an idea of what your team can do, as individual members and as a team, you should go after the job.  Figure out what it is that needs to be done, get as much domain knowledge as you can cram into your head quickly, and start breaking it up into smaller parts.  Hopefully you'll have at least one team member who's a domain expert and can help you with this.

After that, it's time to get to work.  Delegate certain tasks to your team members.  Contribute as much of your own effort to the work as you can without interfering with your responsibilities as a coordinator--this will help you earn the respect of the team.

And remember that your main responsibility is to coordinate things.  You're not a general, barking orders to the grunts that are to be obeyed instantly and without question; you're the guide for a group of skilled professionals, a specialist who specializes in the big picture.  Your team members have their own specialties, so be willing to listen to their ideas and consult with them.  Make it clear that they're free to come to you with ideas and concerns, but also that as the leader, the buck stops with you.  Sometimes you'll have to make a decision between two seemingly-good alternatives, (or two alternatives that different team members each think is good,) and the final decision--and the responsibility for it--rests on your shoulders.

Basically, stay out of the way as much as possible and try to make sure your team members are able to do the best work they can, and they'll love you for it.

ContentLicense: CC BY-SA 2.5


问:
Define Interface Simplicity vs Implementation Simplicity
In Richard Gabriel's The Rise of "Worse is Better", he talks about the simplicity of interface vs the simplicity of implementation in a design.

I've never been able to quite grasp what he means and searching the web for the answer has only yielded information about Java's interfaces (the structure of classes, etc) vs the code in Java's methods and classes.

What does he mean by interface and implementation and what does simplicity mean for each of them?

答:
What does he mean by interface and implementation and what does simplicity mean for each of them?

Don't think too much about it, it's just English.

He means your code's interface (not necessarily interfaces!) - how people work with your code. And your code's implementation - how your code actually does the things it needs to do. And simple is simple - is your stuff easy to work with.

Simplicity in interface means it's easy to use your stuff. Do your functions have good names with obvious parameters and few side effects? Do they do what your users need? Do your classes have good names with obvious functionality? Do they do what your users need? Without too much trouble?

Simplicity in implementation means it's easy for programmers (or you) to work with your stuff. Can you modify the code easily? Can you test it easily? Can you understand it? Debug it?

While simple implementation often yields simple interface, it's not always the case. Some of the best designs isolate bits of necessarily complex implementation behind a simple interface. Likewise, if the easiest implementation isn't what your users need, you can end up with a complex interface.


答:
The page seems to be using those terms literally, without reference to any particular programming construct, so there isn't really anything to define. Instead I'll try giving an example.

Say you have a class that gets things from the internet. Here's a simple interface version:

```<code>class Internet {
    int sendRequest(const std::string& url, std::string& response);
}

Internet::sendRequest(const std::string& url, std::string& response) {
    // parse the url into its various tokens
    m_protocol = /* first token, or https if not provided */
    m_domain = /* second token */
    while(...) { m_parameters.push_back(/* another token */); }
    ...
    switch(m_protocol) {
        case HTTPS: HTTPSImpl.request(m_domain, ...); break;
        ...
    }
}
</code>```

Here's a simple implementation version:

```<code>class Internet {
    int setProtocol(Internet::Protocol protocol);
    int setDomain(const std::string& domain);
    int addParameter(...);
    ...
    int sendRequest(std::string& response);
}

Internet::request(std::string& response) {
    switch(protocol) {
        case HTTPS: HTTPSImpl.request(m_domain, ...); break;
        ...
    }
}
</code>```

Essentially it's a trade-off between making the implementer deal with the complexity versus the interface user. Most of the time you'll be (rightfully) told that hiding complexity from the user is a good thing, but Richard Gabriel's page argues that that might not always be the case.

Title: Define Interface Simplicity vs Implementation Simplicity

Body:
In Richard Gabriel's The Rise of "Worse is Better", he talks about the simplicity of interface vs the simplicity of implementation in a design.

I've never been able to quite grasp what he means and searching the web for the answer has only yielded information about Java's interfaces (the structure of classes, etc) vs the code in Java's methods and classes.

What does he mean by interface and implementation and what does simplicity mean for each of them?

Body:
The page seems to be using those terms literally, without reference to any particular programming construct, so there isn't really anything to define. Instead I'll try giving an example.

Say you have a class that gets things from the internet. Here's a simple interface version:

class Internet {
    int sendRequest(const std::string& url, std::string& response);
}

Internet::sendRequest(const std::string& url, std::string& response) {
    // parse the url into its various tokens
    m_protocol = /* first token, or https if not provided */
    m_domain = /* second token */
    while(...) { m_parameters.push_back(/* another token */); }
    ...
    switch(m_protocol) {
        case HTTPS: HTTPSImpl.request(m_domain, ...); break;
        ...
    }
}

Here's a simple implementation version:

class Internet {
    int setProtocol(Internet::Protocol protocol);
    int setDomain(const std::string& domain);
    int addParameter(...);
    ...
    int sendRequest(std::string& response);
}

Internet::request(std::string& response) {
    switch(protocol) {
        case HTTPS: HTTPSImpl.request(m_domain, ...); break;
        ...
    }
}

Essentially it's a trade-off between making the implementer deal with the complexity versus the interface user. Most of the time you'll be (rightfully) told that hiding complexity from the user is a good thing, but Richard Gabriel's page argues that that might not always be the case.


问:
YAGNI principle put to practice
I recently came across to this principle and so far it is clear the fact that doing things that you don't need at the moment is not feasible as they might not be used or might be changed.

That being said, consider the following scenario: You're working on an application that needs to display text in labels, in several places/parts. The targeted language is English, and there is no requirement to implement multi-language. At this point, if you needed multi-language feature, you'd define every string in a resource file (let's say it's an XML file) and create/use a class to read them and assign them to the corresponding labels (according to the language). Thing is, since multi-language is not a requirement, YAGNI.

So, do you still define strings into a resource file and implement the reader, or you hard-code them and reafactor when you actually need it?

答:
Hard code and refactor when you need it.  Time is money, yadda-yadda, is it worth the time/money to have the unused feature?

Also, it's not hard to do later as much as it is tedious.  Pawn that task off to a junior developer when the need arises.

Finally, when the time comes, some automated tools may get you most of the way there.  Such as Eclipse's string externalizer.

Title: YAGNI principle put to practice


答:
A team lead has a few responsibilities, such as organizing the team, making sure stuff gets done on time, and representing the team to management.

At the end of the day, if the team lead helps the team become better, they will earn the respect.  Becoming better can be in the form of mentoring, helping with time/priority management, and produce quality software on time.  If a team lead is coming in cold, they'll have to be a quick study.

Bottom line is:

Lead be example--brow beating is counter productive in every situation

Introduce any changes to process in a controlled pace

Listen to and incorporate input from your team

Identify one quick win to improve the team and implement it.  And do it again.

Communicate clearly and ask questions often

Title: How to earn team members respect as team lead

Body:
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>


答:
With just a few exceptions, code, data and configuration should be separated. Hard-coding is generally considered a bad practice. You should put UI text into separate file just so you know where to find it, not because you might need i18n. This will not take much longer than hard-coding, but maintainability will be better.

Also with external resource file you will be able to change text without rebuilding/redeploying an app. This may be the case for web apps, for example.

So, this is not breaking YAGNI, but just following other principles/practices.

Title: YAGNI principle put to practice

Body:
I recently came across to this principle and so far it is clear the fact that doing things that you don't need at the moment is not feasible as they might not be used or might be changed.

That being said, consider the following scenario: You're working on an application that needs to display text in labels, in several places/parts. The targeted language is English, and there is no requirement to implement multi-language. At this point, if you needed multi-language feature, you'd define every string in a resource file (let's say it's an XML file) and create/use a class to read them and assign them to the corresponding labels (according to the language). Thing is, since multi-language is not a requirement, YAGNI.

So, do you still define strings into a resource file and implement the reader, or you hard-code them and reafactor when you actually need it?


问:
With AMD style modules in JavaScript is there any benefit to namespaces?
Coming from C++ originally and seeing lots of Java programmers doing the same we brought namespaces to JavaScript. See Google's closure library as an example where they have a main namespace, goog and under that many more namespaces like goog.async, goog.graphics

But now, having learned the AMD style of requiring modules it seems like namespaces are kind of pointless in JavaScript. Not only pointless but even arguably an anti-pattern.

What is AMD? It's a way of defining and including modules that removes all direct dependencies. Effectively you do this

```<code>// some/module.js
define([
    'name/of/needed/module',
    'name/of/someother/needed/module',
  ], function(
     RefToNeededModule,
     RefToSomeOtherNeededModule) {

  ...code...

  return object or function
});
</code>```

This format lets the AMD support code know that this module needs name/of/needed/module.js and name/of/someother/needed/module.js loaded. The AMD code can load all the modules and then, assuming no circular dependencies, call the define function on each module in the correct order, record the object/function returned by the module as it calls them, and then call any other modules' define function with references to those modules.

This seems to remove any need for namespaces. In your own code you can call the reference to any other module anything you want. For example if you had 2 string libraries, even if they define similar functions, as long as they follow the AMD pattern you can easily use both in the same module. No need for namespaces to solve that.

It also means there's no hard coded dependencies. For example in Google's closure any module could directly reference another module with something like var value = goog.math.someMathFunc(otherValue) and if you're unlucky it will magically work where as with AMD style you'd have to explicitly include the math library otherwise the module wouldn't have a reference to it since there are no globals with AMD.

On top of that dependency injection for testing becomes easy. None of the code in the AMD module references things by namespace so there is no hardcoded namespace paths, you can easily mock classes at testing time.

Is there any other point to namespaces or is that something that C++ / Java programmers are bringing to JavaScript that arguably doesn't really belong?

答:
For the HTTP requests, use a combohandler my friend. :)
Very simple either in PHP/NodeJS and makes cache-ing trivial. Most AMD module loading frameworks have one available, it is almost a given.

As an example:
https://www.npmjs.com/package/combohandler-patched

It is only through lack of knowledge that AMD apps (or any for that matter) do not have things such as server-side combohandlers (or even client-side ones, if it had to be monkey patched enough).

In addition, most AMD style libraries (e.g. Dojo) allow for namespaces particularly for the benefit of fixing the issues which were mentioned above where you can create a loader configuration that renames these things.


问:
Repository Pattern and custom queries/REST API. Is it the right approach?
I'm in the early stages of working on an application that is using the Repository Pattern to provide a data access abstraction. This application will have some form of a simple REST API but I'm not sure how to approach this using repositories. To illustrate this, a typical (very simplified) example of a repository is something like this:

<?php
$repo = new PostRepository(); // this would be resolved from an IoC container
$post = $repo->getByEmail('foo@wherever.com');
```

<p>or maybe a little less rigid, like this:</p>

<pre class="lang-php prettyprint-override"><code>$post = $repo->getBy('first_name', 'Bob');
</code>```

But the pattern doesn't seem suited to anything more complicated like, say, the query from this url:

api.example.com/posts?firstName=Bob&lastName=Doe&email=foo@example.com&with=comments
```

It seems like to handle stuff like that (let alone any much more complicated queries that many APIs support) you would pretty much end up having to reimplement the underlying ORM, or create a very leaky abstraction, neither of which seems ideal. Am I going about this wrong?

答:
You need to use some kind of query builder or Criteria API. It might look like this:

```<code>Criteria $criteria = new CriteriaBuilder()
    ->where('firstName', '=', $firstName)
    ->and('lastName', '=', $lastName)
    ->build();
$user = $repo->fetchOne($criteria);
</code>```

This is just imaginary example, but most widely-used frameworks already have such tools:

Doctrine

Laravel

Kohana, etc.

Don't re-implement the underlying ORM, just use API it provides. If it doesn't, choose another one which does.

Methods like $repo->findById($id) may also be helpful if your REST API has resources like api.example.com/posts/123, where you get entity by just using primary key.

Body:
You need to use some kind of query builder or Criteria API. It might look like this:

Criteria $criteria = new CriteriaBuilder()
    ->where('firstName', '=', $firstName)
    ->and('lastName', '=', $lastName)
    ->build();
$user = $repo->fetchOne($criteria);

This is just imaginary example, but most widely-used frameworks already have such tools:

Doctrine

Laravel

Kohana, etc.

Don't re-implement the underlying ORM, just use API it provides. If it doesn't, choose another one which does.

Methods like $repo->findById($id) may also be helpful if your REST API has resources like api.example.com/posts/123, where you get entity by just using primary key.


问:
What is a better design a light weight user or a heavy weight heavy user model?
This is a design question and I am confused about how to design my user  object. As in most systems, user is the central part of my application  and a lot of information scattered around my database points back to the user for example a user can have multiple orders, mulitple Addresses, and he may have won multiple prizes. If we want to talk about ONLY user and his basic information we can be done with ID, firstnmae, lastname etc. So I have two clear choices

Create a light weight  user object which looks like following:

```<code> public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
}
</code>```

and get all the infromation at the other information at the run time like orders and Prizes on need basis.

OR

Design a more contained object which carries all the required information with it but is little heavy:

```<code>public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
  public Address HomeAddress {get;set;}
  public List<Prizes> Prizes {get;set;}

}
</code>```

Which Does any design model align to a good design philosophy? Are there any best practices in the kind of situation that can help me make a decision?

答: The second design is almost certainly better than the first, unless SomeMoreInformation is both very expensive and entirely optional.


答:
I think beyond the technical question, your boss may not have the time to keep up to date on current standards.

Since his stance is not completely out to lunch, just out-dated, respect his position when discussing this matter (and you need to remember to discuss, not argue), and try to work through concerns he has with regards to UTF-8.  I suspect the underlying issue is not a technical issue and may require some level of soft-skill negotiation.