问:
When are you violating a license like the GPL?
Specifically in the following scenarios where you're working on an open source library using an incompatible license like the MIT license.

You copy & paste a method from a GPL library - blatantly a violation assuming the GPL library created the method themselves.

You create a function with a similar purpose but you create it from scratch - presumably not a violation

You use the same code as a GPL library, but you improve on it (optimize performance for example) - is this a violation?

You use the same code as a GPL library, but you superficially refactor it (e.g. rename variables for clarity, add comments, but don't really change the underlying logic) - is this a violation?

You translate code from a GPL library to another language but keep the logic exactly the same - presumably not a violation?

I know these are possibly questions for lawyers but I'm hoping to get a rough idea.

答:
(...) using an incompatible license like the MIT license.

In general, I like to work with this baseline:

GPL + MIT => GPL

MIT + GPL => GPL

(anything else) + GPL => GPL

GPL + (anything else) => GPL

In other words, if you mix GPL with anything else, you get GPL'ed code. There are some exceptions, but not at the level of actually mixing code. Note that you can do as you please as long as you keep the code to yourself -- only when you distribute your code you must adhere to the rules of the GPL.

You copy & paste a method from a GPL library - blatantly a violation assuming the GPL library created the method themselves.

Not a violation as long as you release your code under the GPL and quote the original author. This is called a derivative work (one that has all parts but one removed).

You create a function with a similar purpose but you create it from scratch -
  presumably not a violation

If you see a GPLed program and think to yourself, "gee, that would be useful if it were not GPLed" and the go and write your own program without copying any code and other protected parts, probably not a direct violation. Very much depends on the jurisdiction.

You use the same code as a GPL library, but you improve on it (optimize performance for example) - is this a violation?

As long as you put your code under the GPL that's one of the core ideas of GPL - allow you to improve on the previous work, freely, as you see fit. As long as you stick to the rules, of course.

You use the same code as a GPL library, but you superficially refactor it (e.g. rename variables for clarity, add comments, but don't really change the underlying logic) - is this a violation?

Again, as long as you keep the result GPL'ed and quoting the original author, that's probably fine.

You translate code from a GPL library to another language but keep the logic exactly the same - presumably not a violation?

It's still copying, right? If your intention is to take a GPL'd program in language A and transform it to language B just to get rid of the GPL, think again. That is at least plagiarism, if not worse, in most jurisdictions.

Disclaimer: IANAL


答:
You violate the GPL when you do two things.

Create a "derivative work" from GPL'd code.

Fail to follow the requirements of the GPL for creating such works.

You can in fact do ALL of what you noted, so long as you follow the GPL's rules.  That's the point of copyleft.  You can copy and paste all or part of a GPL'd program into your own, modify it to suit your purposes better, or completely re-write it, and so long as you do what the GPL requires you're 100% in the clear.

If you don't want to follow the GPL's requirements, what you can do becomes far more restrictive.  In fact, it becomes exactly as restrictive as what you could do if someone emailed you the source code to some closed-source program, like Microsoft Windows 10.

ContentLicense: CC BY-SA 3.0

Title: When are you violating a license like the GPL?

Body:
Specifically in the following scenarios where you're working on an open source library using an incompatible license like the MIT license.

You copy & paste a method from a GPL library - blatantly a violation assuming the GPL library created the method themselves.

You create a function with a similar purpose but you create it from scratch - presumably not a violation

You use the same code as a GPL library, but you improve on it (optimize performance for example) - is this a violation?

You use the same code as a GPL library, but you superficially refactor it (e.g. rename variables for clarity, add comments, but don't really change the underlying logic) - is this a violation?

You translate code from a GPL library to another language but keep the logic exactly the same - presumably not a violation?

I know these are possibly questions for lawyers but I'm hoping to get a rough idea.


问:
Why would many duck-typed dynamic programming languages use a class-based approach instead of prototype-based OOP?
Since quite many dynamic programming languages have the feature of duck typing, and they can also open up and modify class or instance methods at anytime (like Ruby and Python), then…

Question 1)
What’s the need for a class in a dynamic language? Why is the language designed that way to use a class as some kind of “template” instead of do it the prototype-way and just use an object?

Also JavaScript is prototyped-based, but CoffeeScript (the enhanced version of JavaScript) chooses the class-based way. And it goes the same for Lua (prototyped-based) and MoonScript (class-based). In addition, there’s class in ES 6. So…

Question 2)
Is it suggesting that if you try to improve a prototype-based language, among other things, you should change it to class-based? If not, why is it designed that way?

答:
Many programmers prefer working with classes. It's a very easy-to-understand concept that is a good model of human thought processes about the world (that is, we instinctively relate real objects to the abstract group of items we consider them to belong to, which is what a class is). Also, classes make reasoning about object types easier: in a class-based language, applying principles like Liskov substitution is simpler than it is in a language where we just have objects that may have different methods, or whose type may even change at run time, as is the case in JavaScript.

Note that even in JavaScript, an awful lot of code simply uses the prototype facility to emulate classes. This is mostly because a lot of programmers prefer thinking that way.

There is also another reason class-based languages are preferred: it is easier to compile them to efficient code. The most efficient JavaScript VMs effectively dynamically create classes to represent the types of JavaScript objects as their methods and prototypes change. See this description of V8's implementation for a rationale on why this is done.


问:
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>

答:
There are 4 traits common among followers that I'd point out:

Build trust - This takes time and experiences as some people are trusting right off the bat and others can take time to open up and stuff.  The key point here is to be open and honest I'd think.

Show compassion - How well do you care about these people?  How do you show that?  Being there for them is part of this but there are a lot of other dimensions to the relationship to note here.

Provide stability - Many people don't like change and don't like adapting to new things.  Others are fine with it but you have to know people first and foremost.

Create hope - This is a funny thing that may or may not be realistic in your case.  This is about giving someone something to live for and isn't necessarily an easy thing to do.

I'd also recommend looking up, "How to Win Friends and Influence People," for more ideas about dealing with people.

ContentLicense: CC BY-SA 2.5


问:
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?

答:
What you ask relates to code complexity, time vs space tradeoffs, caching strategy (if any), and round-trips to the database.

In general, I tend to start with the first, simple approach.  Then, when and where performance requirements dictate it, I'll move toward the second approach.

Key point: Depending on usage and caching strategy, this move may never be required.

Finally, when moving in this direction, when you are querying a one-to-many relationship (like each user has a set of email addresses), it may be possible to fetch the user(s) and all associated email addresses in one round-trip to the database.  This is where significant performance gains can come into play, especially when there is higher latency between application and database.


问:
Algorithm for merging multiple rows of data
I need an algorithm to merge multiple rows for data, where one column is the index column and if one or more rows have the same index value merge the column values into a single row, and lastly sort the rows one the index column.

ASCII ART Example:

```<code>Starting point:

------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1          | 1        |          |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 1          |          | 1        |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 3          | 1        |          |
------------------------------------

Outcome:

------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1          | 1        | 1        |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 3          | 1        |          |
------------------------------------
</code>```

As you can see the empty columns have been merged, duplicates have been discarded and rows have been sorted on the index column. (NOTE: The column values should not add to each other.)

I have been trying to come up with an efficient algorithm for this but so far I think I have failed as i think its pretty ineffective and also its not working correctly.

Here I have some code to show you what I currently have, the first code pieces are just POCO objects to give you an idea of what I'm working with, have also included equal methods for you to see how I compare objects.

```<code>public interface IWitsmlLogCurveInfo
{
    string Mnemonic { get; set; }
    bool IndexCurve { get; set; }
}

public class WitsmlLogCurveInfo
{
    string Mnemonic { get; set; }
    bool IndexCurve { get; set; }

    protected bool Equals(WitsmlLogCurveInfo other)
    {
        return string.Equals(Mnemonic, other.Mnemonic);
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogCurveInfo)obj);
    }

    public override int GetHashCode()
    {
        return (Mnemonic != null ? Mnemonic.GetHashCode() : 0);
    }
}

public interface IWitsmlLogDataColumn
{
    IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
    string Value { get; set; }
}

public class WitsmlLogDataColumn : IWitsmlLogDataColumn
{
    public IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
    public string Value { get; set; }

    protected bool Equals(WitsmlLogDataColumn other)
    {
        return string.Equals(Value, other.Value) && string.Equals(WitsmlLogCurveInfo, other.WitsmlLogCurveInfo);
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogDataColumn)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((Value != null ? Value.GetHashCode() : 0) * 397) ^ (WitsmlLogCurveInfo != null ? WitsmlLogCurveInfo.GetHashCode() : 0);
        }
    }
}

public interface IWitsmlLogDataRow
{
    IList<IWitsmlLogDataColumn> Columns { get; set; }
    IWitsmlLogDataColumn GetIndexColumn();
}

public class WitsmlLogDataRow : IWitsmlLogDataRow
{
    public IList<IWitsmlLogDataColumn> Columns { get; set; }

    public IWitsmlLogDataColumn GetIndexColumn()
    {
        return Columns.SingleOrDefault(x => x.WitsmlLogCurveInfo.IndexCurve);
    }

    protected bool Equals(WitsmlLogDataRow other)
    {
        return Columns.All(x => other.Columns.Contains(x));
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogDataRow)obj);
    }

    public override int GetHashCode()
    {
        return (Columns != null ? Columns.GetHashCode() : 0);
    }
}

public enum FrictionType
{
    Annulus,
    Sliding,
    Rotating
}

public interface IWitsmlLogFriction
{
    FrictionType Type { get; set; }
    IList<IWitsmlLogDataRow> Rows { get; set; }
}

public class WitsmlLogFriction : IWitsmlLogFriction
{
    public FrictionType Type { get; set; }
    public IList<IWitsmlLogDataRow> Rows { get; set; }

    public override string ToString()
    {
        return string.Format("FrictionType: {0}", Type);
    }

    protected bool Equals(WitsmlLogFriction other)
    {
        return Type == other.Type && Rows.All(x => other.Rows.Contains(x));
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogFriction)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((int)Type * 397) ^ (Rows != null ? Rows.GetHashCode() : 0);
        }
    }
}
</code>```

Here is the Algorithm Function itself:

```<code>private IList<IWitsmlLogDataRow> CombineMultipleFrictionTypes(IList<WitsmlLogFriction> witsmlLogFrictions, WitsmlLogCurveInfo indexCurve)
{
    if(indexCurve == null)
    {
        throw new NoNullAllowedException("IndexCurve can not be null!");
    }
    if(witsmlLogFrictions.Count == 1)
    {
        return witsmlLogFrictions.First().Rows;
    }
    WitsmlLogFriction witsmlLogFrictionA = witsmlLogFrictions.FirstOrDefault();
    List<IWitsmlLogDataRow> rows = new List<IWitsmlLogDataRow>();
    if (witsmlLogFrictionA == null)
    {
        return rows;
    }
    foreach(WitsmlLogFriction witsmlLogFrictionB in witsmlLogFrictions.Where(witsmlLogFriction => witsmlLogFriction.Type != witsmlLogFrictionA.Type))
    {
        foreach (IWitsmlLogDataRow witsmlLogDataRowA in witsmlLogFrictionA.Rows)
        {
            // Get index curve for row A
            IWitsmlLogDataColumn indexCurveA = witsmlLogDataRowA.GetIndexColumn();
            if (indexCurveA == null) continue;

            IWitsmlLogDataRow tempWitsmlLogDataRowA = new WitsmlLogDataRow(witsmlLogDataRowA.Columns);
            foreach(IWitsmlLogDataRow witsmlLogDataRowB in witsmlLogFrictionB.Rows)
            {
                // Get index curve for row B
                IWitsmlLogDataColumn indexCurveB = witsmlLogDataRowB.GetIndexColumn();
                if (indexCurveB == null) continue;

                // Compare index curve values
                if(indexCurveA.Equals(indexCurveB))
                {
                    // Index curve values are identical, append columns from row B onto row A, except row B's index column
                    foreach(IWitsmlLogDataColumn column in witsmlLogDataRowB.Columns.Where(column => !column.WitsmlLogCurveInfo.Equals(indexCurve)))
                    {
                        tempWitsmlLogDataRowA.Columns.Add(column);
                    }
                }
                else
                {
                    rows.Add(witsmlLogDataRowB);
                }
            }
            // Add the new row
            rows.Add(tempWitsmlLogDataRowA);
        }
    }
    switch(indexCurve.IndexType)
    {
        case LogIndexType.datetime:
            return rows.OrderBy(x => Convert.ToDateTime(x.GetIndexColumn().Value)).ToList();
        default:
            throw new ArgumentOutOfRangeException("indexCurve", "IndexType: " + indexCurve.IndexType + " is not supported.");
    }
}
</code>```

The problem is I think its pretty ineffective, but it could also be the only way to do it, and it adds more data then it should. What would be a better and efficient way to solve this?

答:
Since you need to sort the values on the index I would select SortedDictionary, and I will keep the merging logic inside the Row object,

```<code>public class Row
{
    public int Index { get; set; }
    public string IndexA { get; set; }
    public string IndexB { get; set; }

    public void Merge (Row other}
    {
        if (Index != other.Index}
            throw new Exception("Cannot merge");

        If (string.isNullOrEmpty(IndexA))
            IndexA = other.IndexA;

        //any other merge logic
    }
}
</code>```

This code can be used to go through rows and merge them,

```<code>IList<Row> MergeAndSort(IList<Row> rows)
{
   var dic = new SortedDictionary<int,Row>();
   foreach(Row row in rows)
   {
       if (dic[row.Index] == null)
           dic[row.Index] = row;
       else
           dic[row.Index].Merge(row);
   }
   return dic.SelectMany (d => d.Value).ToList();
}
</code>```

Body:
Since you need to sort the values on the index I would select SortedDictionary, and I will keep the merging logic inside the Row object,

public class Row
{
    public int Index { get; set; }
    public string IndexA { get; set; }
    public string IndexB { get; set; }

    public void Merge (Row other}
    {
        if (Index != other.Index}
            throw new Exception("Cannot merge");

        If (string.isNullOrEmpty(IndexA))
            IndexA = other.IndexA;

        //any other merge logic
    }
}

This code can be used to go through rows and merge them,

IList<Row> MergeAndSort(IList<Row> rows)
{
   var dic = new SortedDictionary<int,Row>();
   foreach(Row row in rows)
   {
       if (dic[row.Index] == null)
           dic[row.Index] = row;
       else
           dic[row.Index].Merge(row);
   }
   return dic.SelectMany (d => d.Value).ToList();
}


问:
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?

答:
Sounds like you are doing too much in the send method, where ideally it should be only used to send email but not to do processing like mail merge, However without seeing your method signatures I can't say that for sure.

Using a lot of overloads with default values will often cause a lot of confusion especially if it's not done proper manner.

One way to avoid this is to use a DTO object to pass into the method instead of using overloads. You can create a single method and use a DTO to pass in values to the method.

Title: Avoiding a large amount of overloads


问:
Combining Patterns: Fluent Builder and Null Object Pattern
I am currently wrestling around with some GUI code where I have a table whose rows correspond to some object, let's say a Person object. When the table initializes, it fills the table with the Person objects that it knows about - say Bob, Andy, and Tom. The rest of the rows item's (row.getItem()) are null. In this particular GUI framework, one cannot highlight/select rows who's getItem() returns null - but in my particular use case I want to allow this functionality.

Therefore, upon initializing the table, I want to set the rows after Bob, Andy, and Tom to a Person object that represents a empty/null Person (not initialized per se), hence the null object pattern coming into play. The patterns combine because the Person class uses the fluent builder pattern for constructing Person instances, so I thought about combining the two like so:

```<code>for (rows in table) {
    if (row.getItem() == null) {
        row.setItem( Person.PersonBuilder().nullObject().build() );
    }
}
</code>```

I am looking for feedback/advice on the merits of this choice, and am welcome to alternatives if this approach is flawed.

答:
With your approach one of the problems will be to check if a row contains a null object.
I'd go with a constant object such as Person.NullObject (where it's a static value), with that one advantage is you could always check if the row has a value by checking row.getItem == Person.NullObject but if this approach is used you have to make sure the fields of the Person.NullObject is not going to be modified by in-place editing.


问:
How to handle authentication to web service from mobile?
I'm making a mobile application, and I use JSON Web Token Authentication (JWT Auth), but I have three questions about:

Should I use refresh-tokens or non-expiring access tokens?

In case I use refresh-tokens, when the token expires, should I sign out the user (and force the user to login again) or create a new one and send it back to the app so it can be used for future requests?

How should I save the token on the mobile (database, preferences,etc.)?

Any help and resource about this (books,documents,blog,etc.) would be appreciated, thanks in advance!

答:
1.In case you have a "remember me" option in your page you should use the non-expiring token. Otherwise ,in my opinion you should use the refresh one.

2.Token expiration should be handled  by asking the user to login again. The tricky part is when the token expires while the user is in the middle of something .In that case you should try remembering what action he was trying to do before the token expired and allow him to continue once he has logged in again.

3.You could use local storage for storing tokens. You can set it to a variable in the storage once authentication is complete and there after keep appending that storage value to the http header of every subsequent protected web service request.


答:
I've heard that on big projects, where teams of people are working together on the same code, that flexible languages (where you can modify an object's properties and methods during run-time) are liberties that other team members don't want you to have.

They want to know, when they are dealing with an object, that the object will act just like the blueprint says, and not some morphed way that some other ambitious developer decided to change it to in order to complete his own task.

So, the only reason I can conceive, that someone wouldn't want the flexibilities offered by these awesome dynamic languages, is that they want to simplify team development, debugging, and auto-documentation.

Personally, I've developed applications in both methodologies, and I get things done way faster with dynamic languages. I do not use any of these frameworks designed to turn my dynamic language back into a class-base language again. Such things are a regression to my tastes.

Title: Why would many duck-typed dynamic programming languages use a class-based approach instead of prototype-based OOP?

Body:
Since quite many dynamic programming languages have the feature of duck typing, and they can also open up and modify class or instance methods at anytime (like Ruby and Python), then…

Question 1)
What’s the need for a class in a dynamic language? Why is the language designed that way to use a class as some kind of “template” instead of do it the prototype-way and just use an object?

Also JavaScript is prototyped-based, but CoffeeScript (the enhanced version of JavaScript) chooses the class-based way. And it goes the same for Lua (prototyped-based) and MoonScript (class-based). In addition, there’s class in ES 6. So…

Question 2)
Is it suggesting that if you try to improve a prototype-based language, among other things, you should change it to class-based? If not, why is it designed that way?


问:
RESTful Backend - How coupled should my back end and front end be?
I'm creating a web application with a front end client written in angular as well as a back end that I'm writing in Django (there are reasons I picked the frameworks but they are irrelevant to my question).

I have my front end planned out down to every page that will be available. I currently am only going to implement the angular cient but in the future I plan on implementing a native android and iOS app for learning purposes.

My question is how coupled should my back end design be with my front end client?

Should I design my endpoints on a per view basis?
This seems like back end will need work when I create another client.

Or should my endpoints be more focused around exposing CRUD functionality for my models?
This seems like it would leave room for creativity and make the back end more flexible.

These are a few of the questions I have been asking myself and I provided them to add a little more scope to my question.

Even if I went with the crud approach it seems like I will still be implementing specialized endpoints for handling common application features.

Thanks in advance.

答:
If each client you intend to service requires different output from your back end. Then write your back-end in a way where is can serve each type.

Do some abstraction. Ask yourself, what things will all clients need the same way, and what things will each client need in a specific different way.

Put all the stuff that is the same for all clients together, and then write an interface for each client that handles the differences for that client. These interfaces will get all content from the same module, but adapt serving that content to the specific clients needs.


答:
Question 1) What’s the need for a Class in a dynamic language? Why the language is designed that way to use a class as some kind of “template” instead of do it the prototype-way and just use a object?

The very first OO language (even though it wasn't called "OO"), Simula, didn't have inheritance. Inheritance was added in Simula-67, and it was based on classes.

Around the same time, Alan Kay started working on his idea of a new programming paradigm, which he later named "Object-Orientation". He really liked inheritance and wanted to have it in his language, but he also really disliked classes. However, he couldn't come up with a way to have inheritance without classes, and so he decided that he disliked classes more than he liked inheritance and designed the first version of Smalltalk, Smalltalk-72 without classes and thus without inheritance.

A couple of months later, Dan Ingalls came up with a design of classes, where the classes themselves were objects, namely instances of metaclasses. Alan Kay found this design slightly less appaling than the older ones, so Smalltalk-74 was designed with classes and with inheritance based on classes.

After Smalltalk-74, Alan Kay felt that Smalltalk was moving in the wrong direction and didn't actually represent what OO was all about, and he proposed that the team abandon Smalltalk and started fresh, but he was outvoted. Thus followed Smalltalk-76, Smalltalk-80 (the first version of Smalltalk to be released to researchers), and finally Smalltalk-80 V2.0 (the first version to be released commercially, and the version which became the basis for ANSI Smalltalk).

Since Simula-67 and Smalltalk-80 are considered the grandparents of all OO languages, almost all languages that followed, blindly copied the design of classes and inheritance based on classes. A couple of years later, when other ideas like inheritance based on mixins instead of classes, and delegation based on objects instead of inheritance based on classes surfaced, class-based inheritance had already become too entrenched.

Interestingly enough, Alan Kay's current language is based on prototype delegation.


问:
Controller in MVC
Alright so it is an essential part of OOP that one class should only do one thing, and it makes sense. In practice I've seen that classes which don't obey this rule get thick and cluttered.

So I was thinking and I kinda can't wrap my head around how the controller fits into this. If each method of a controller should represent a different page from the website, then this doesn't really make much sense to me. Yes the pages may be related, such as /user/edit and /user/view which are in the same controller, but if I'm going to display one of those pages, loading the other method and possibly many more is completely pointless.

It's probably that I'm missing something since people have been using this approach in major frameworks, but can you help me figure out what?

答:
I think you are referring to the Single Responsibility Principle (SRP).  Which, in summary states:

that every class should have a single responsibility, and that
  responsibility should be entirely encapsulated by the class

However, this does not mean that one class should only do a single thing. In means that a class or module should only have one reason to change:

Robert C. Martin defines a responsibility as a reason to change, and
  concludes that a class or module should have one, and only one, reason
  to change.

So, in your example of /user/edit and /user/view, the controller is responsible for exposing user to something beyond the boundary of the application, like a view.

The higher in the stack you get (or the more you aggregate for viewing), the more you implicitly depend on.  MVC pattern is a way to minimize this.  By separating responsibilities when preparing data for viewing.  MVC can further be split into vertical slices in your application (user for example).  This moving the design of the application more and more towards SRP.  This is kind of the best that we have at the moment.  There are other patterns (like MVP, and MVVM) and maybe one day a better one will emerge and be adopted.

SRP is a principle, which means we should consider and strive towards it when designing applications.  But we also have to be pragmatic and get things done.  So, there is a trade off.

Title: Controller in MVC


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
I was working on a big project in 1996 where we were scoring live sporting events.  This conversation happened:

Boss: Go out to the venue for the next event.

Me: What do you need me to do.

Boss: Be there just in case.

Me: Just in case what?

Boss: In case the tech lead loses it.  He's way too stressed out and I don't know what he
might do.

Me: And if he loses it, what do you want me to do?

Boss: Just get him out of there so everyone else can continue working.  I don't care how you do it.

OwnerDisplayName: DaveJ


答:
Well, I recently went through a situation just like yours. All "do's" listed here worked very well for me, plus one big "don't":

Don't me a menace to the people on the team. You are there to make them work better and show their values, not yours.

As the leader and senior developer on a team, usually we human beings try to accomplish too much, and not delegate very well. Trust them. Even if they make mistakes. Specially if they make mistakes. This is part of their personal grown.

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>


问:
Would redrawing controls in c# give more performance?
Now I realize this is a kind of weird question but here it is:
Let us assume I redraw all the controls by myself rather than using the default provided ones (Obviously I'm talking of winforms as WPF is already a custom drawn control set and winforms are just a way to access the Win32 API). Now I make an application with my custom-drawn controls. Then I make an application with winforms, which, in turn, uses the Win32 API. Now, when I run both the applications, will there be any performance difference? If yes, which will perform better?

Now comes the main question:
How (and based on what factor(s)) do you decide / predict as to which will perform better?

P.S. Forgive me if I am not clear enough. I always have trouble expressing my thoughts.

答:
You don't "decide/predict" those things. Similarly, you don't predict where a bottleneck is.

If you need to know which solution is faster, you do both, and then compare the benchmarking results.

You understand that the result will depend, among others, on how good your optimization skills are compared to the skills of Microsoft developers, and we can't possibly know how good you are, right?

There are many parameters involved in performance: your profiling/optimization skills, but also purely technical ones, like the number of layers of abstraction. You may obtain excellent performance results for a home-made solution made during a weekend. Or you may spend months profiling and optimizing your app and still be behind .NET Framework's performance. Unless you actually do the test, you can't know the answer.


问:
What is best practice to handle whitespaces when letting the user edit the configuration, the name=value pairs?
For instance, you let the user define the notorious path variable. How do you interpret apppath = C:\Program Files\App?

This looks like a programming language adopted practice to ignore the white spaces and you leave them around the equality mark for readability, but it might be a valid variable value with white space in the application (consider, it is a suffix).

Even keys can contain whitespaces, can't they?

What is the general best practice for my application? If I have:

```<code>key-example = value-example
</code>```

should I interpret the key being "key-example" or "key-example " and the value as being "value-example" or " value-example"?

答:
It's up to you to define the rules for your app.

For instance, you may define that:

Whitespace before or after the equality sign is ignored,

Whitespace inside the key is forbidden,

Whitespace inside the value can be used only if the value is enclosed in quotes, so:

```<code>say-hello = Hello, World!
</code>```

is forbidden, while:

```<code>say-hello = "Hello, World!"
</code>```

is allowed, which also makes it possible to have whitespace prefixes:

```<code>say-hello = "    Indentation is sweet."
</code>```

Defining a format may be a complex task. For instance:

How do you escape quotes?

How do you escape the escape character you use to escape quotes?

How do you handle empty values?

What is the maximum length of a key? What about a value?

How do you handle multiline values?

What about whitespace Unicode characters other than a space (such as a non-breaking space character)?

What about Unicode characters which are usually not displayed on the screen? For instance, how do you deal with Unicode categories Cf or Zl?

What are the characters allowed in the key? For example, is:

```<code>'
</code>```

a valid key?

Should the following line work?¹

```<code>say-hello ꘌ "Hello, World!"
</code>```

Hint: the equality sign is not an equality sign, but the character 0xa60c (Vai syllable lengthener). Although few people would use this symbol instead of the equality, the more frequent case is a copy-paste from Microsoft Word (watch closely the quotation marks):

```<code>say-hello = “Hello, World!”
</code>```

etc.

This is why, unless you are completely sure that you can define a format and describe it precisely and verbosely, use a format which already exists.

JSON or XML are commonly used formats you can use in nearly every programming language. You may even abstract the underlying format by using a database. Redis, for instance, is a popular solution for key-value store.

¹ Chrome users using Windows would probably see a question mark in a square. With other browsers or with Chrome on Linux, the character appears like an equality sign and can easily be misleading: the only visual difference is that there is a tiny difference in the space between the horizontal bars.

Body:
It's up to you to define the rules for your app.

For instance, you may define that:

Whitespace before or after the equality sign is ignored,

Whitespace inside the key is forbidden,

Whitespace inside the value can be used only if the value is enclosed in quotes, so:

say-hello = Hello, World!

is forbidden, while:

say-hello = "Hello, World!"

is allowed, which also makes it possible to have whitespace prefixes:

say-hello = "    Indentation is sweet."

Defining a format may be a complex task. For instance:

How do you escape quotes?

How do you escape the escape character you use to escape quotes?

How do you handle empty values?

What is the maximum length of a key? What about a value?

How do you handle multiline values?

What about whitespace Unicode characters other than a space (such as a non-breaking space character)?

What about Unicode characters which are usually not displayed on the screen? For instance, how do you deal with Unicode categories Cf or Zl?

What are the characters allowed in the key? For example, is:

'

a valid key?

Should the following line work?¹

say-hello ꘌ "Hello, World!"

Hint: the equality sign is not an equality sign, but the character 0xa60c (Vai syllable lengthener). Although few people would use this symbol instead of the equality, the more frequent case is a copy-paste from Microsoft Word (watch closely the quotation marks):

say-hello = “Hello, World!”

etc.

This is why, unless you are completely sure that you can define a format and describe it precisely and verbosely, use a format which already exists.

JSON or XML are commonly used formats you can use in nearly every programming language. You may even abstract the underlying format by using a database. Redis, for instance, is a popular solution for key-value store.

¹ Chrome users using Windows would probably see a question mark in a square. With other browsers or with Chrome on Linux, the character appears like an equality sign and can easily be misleading: the only visual difference is that there is a tiny difference in the space between the horizontal bars.


问:
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?)

答:
It is mainly for practical reasons that copyright protection is applied on the level of files and not on change-sets.

First of all, most of the copyright law and the ideas encased in it stem from an era far before electronic copies existed. In those days there was no effective mechanism to make changes to a copyrighted work and only distribute those changes. What was possible is that person B took the work from person A, made some changes to it and distributed the changed version. So, copyright law was written to regulate those kinds of processes.

In addition, many copyright laws impose some minimum amount of originality to the change before the modified version becomes eligible for copyright on its own.

As a result, we now have the following situation:

A single contribution may not be substantive/original enough to qualify for copyright protection (just renaming a variable may not qualify)

If the single contribution is substantive/original enough for copyright protection, then the result of applying the contribution is considered a distinct work for copyright protection, separate from the original work.

If a single person makes several small contributions, each of which is not eligible for copyright protection on its own, it is still possible (and even likely) that the final product contains enough material from that one person to give that person a claim to the copyright on that material.

With that in mind, your proposal has the following practical problems:

As the result of applying all the contributions is considered a copyrightable work under copyright law, allowing different copyright licenses for the different contributions (presuming those contributions are each significant enough) means that each token in a file could be subject to a different copyright license. It will be almost impossible to tell what you will be allowed to do.

As many individual contributions are likely to be too insignificant to be copyrightable in their own right, depending on the jurisdiction, it is impossible to attach license terms to those contributions.

Taken together, several small contributions from one person give that person a claim to the copyright on the resulting file. The license terms will be those of the original copyright license, because the individual contributions were too small to dictate other terms.


答:
@DavinTyon's answer was very good, but I think that there are a couple other things worth mentioning.  For better or for worse, the router/controller part of MVC is functional.  The hierarchy works like this:

The router takes the URL and figures out which function it should call

The controller acts as a module to encapsulate related functions

The action is the specific function that gets called

This fits well with mapping functionality to URI space.  One thing that search engines have taught us is that URIs matter.  They affect our page ranking, and they are contracts to consumers (users or machines) that you can get a resource at this location.

The specific action is a set of instructions on how to prepare the resource for the request.  Mixing functional and object oriented approaches feels disjointed and difficult to wrap your head around in many cases.  Unfortunately, as we build more and more distributed systems, the influence of functional programming will only get greater.

MVC attempts to help bridge that divide:

Controllers are modules of related actions (functions)

Actions prepare resources for the view templates

Models are object oriented and are where you apply all your object oriented principles.

I think this is a better way of wrapping our head around an MVC application, and also helps us find the right patterns and design principles for the various pieces.

One of the main drivers behind MVC was also improving test-ability.  You can run the actions on a controller without a web server or full infrastructure available.  You can also test the contents of the Model and ViewBag that were passed into the View object returnd from an action.  The model remains as testable as you designed it.  The last piece of making sure the view looks right remains a manual process, but the riskiest portions of the app can be fully tested.

Title: Controller in MVC

Body:
Alright so it is an essential part of OOP that one class should only do one thing, and it makes sense. In practice I've seen that classes which don't obey this rule get thick and cluttered.

So I was thinking and I kinda can't wrap my head around how the controller fits into this. If each method of a controller should represent a different page from the website, then this doesn't really make much sense to me. Yes the pages may be related, such as /user/edit and /user/view which are in the same controller, but if I'm going to display one of those pages, loading the other method and possibly many more is completely pointless.

It's probably that I'm missing something since people have been using this approach in major frameworks, but can you help me figure out what?


问:
Literal strings vs. object properties in JavaScript
JavaScript libraries in the same space (UI widgets) use two different approaches for instantiating components:

Literal strings to specify types, and inlining as much as possible, for example:

```<code>var oTable = webix.ui({
    view: "datatable",
    columns: [
        { id: "rank",   header: "", css:"rank", width: 50 },
        { id: "title",  header: "Film title", width: 200 },
        { id: "year",   header: "Released", width: 80 },
        { id: "votes",  header: "Votes", width: 100 }
    ],
    autoheight: true,
    autowidth: true,
    data: tableData
});
</code>```

A complex class hierarchy and passing objects instead of strings:

```<code>var oTable = new sap.ui.table.Table({
    title: "Movies",
});

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Film title"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "title"),
    sortProperty: "title",
    filterProperty: "title",
    width: "200px"
}));

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Released"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "released"),
    sortProperty: "released",
    filterProperty: "released",
    width: "80px"
}));

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Votes"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "votes"),
    sortProperty: "votes",
    filterProperty: "votes",
    width: "100px"
}));

// add the other columns...

var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: tableData});
oTable.setModel(oModel);
oTable.bindRows("/modelData");
</code>```

In both cases, tableData is a plain JSON array, so no differences there:

```<code>[
    { id: 1, title: "Shawshank Redemption", year: 1994, votes: 678790, rank: 1 },
    { id: 2, title: "The Godfather", year: 1972, votes: 511495, rank: 2 }
]
</code>```

What are the advantages and disadvantages of these two approaches, in terms of learning curve, maintainability, avoidance of antipatterns, reusability, and other software engineering best practices?

答:
The latter one is easier to extend and customize, while separating concerns both for the user of the library and the author.  For example, if for some reason it made sense in your application, you could very easily create different columns inside different functions.  For another example, the user could create their own nifty MyLabel and MyTemplate components without the library having to know anything about it.

The former is much simpler to read, write, and maintain, at the expense of being more difficult to customize and extend.  In other words, you're largely stuck with what you're given.  This is a very good thing if what you're given is sufficient for your requirements.  It's a very bad thing otherwise.

It boils down to the YAGNI principle.  If you're pretty sure you will only ever need the standard configurations and their provided customizations, the complexity of the second approach isn't buying you anything.


问:
Which languages are used today for low-level programming?
When I hear low-level programming, such as for drivers, embedded systems, operating systems, etc., I immediately think about C and perhaps C++. But mainly C.

But what other languages are also used for these kind of tasks? Today, I mean, not what has been used.

答:
Well, I did some work on embedded systems through last years using C and Lua.

Check out eLua as well.

--
EDIT: Here in Brazil we do have a "new technology" for Digital TV's, called Ginga. It's really a standard, but in this standard the Lua language is used as one source of embedded language. The other one is Java.

I guess we can cite Java as well, for some special systems like JavaCards. If those are not embedded systems, than I don't know what embedded means... :)


答:
The inline declaration can be easier to read and maintain in simple cases, easier for non-programmer types to understand and maintain, but more difficult to extend or manage dynamic concerns. i.e. in your example, if you want certain columns to only be used in certain circumstances, things start to get ugly and the simplicity and readability are negated in a hurry.

The second approach has a higher learning curve, will make less sense to non-programmers, but makes dynamic concerns straightforward, provides transparency into what is actually happening, and tends to make a greater degree of flexibility and extensibility possible.

An ideal UI library would provide both types of options.

Title: Literal strings vs. object properties in JavaScript

Body:
JavaScript libraries in the same space (UI widgets) use two different approaches for instantiating components:

Literal strings to specify types, and inlining as much as possible, for example:

```<code>var oTable = webix.ui({
    view: "datatable",
    columns: [
        { id: "rank",   header: "", css:"rank", width: 50 },
        { id: "title",  header: "Film title", width: 200 },
        { id: "year",   header: "Released", width: 80 },
        { id: "votes",  header: "Votes", width: 100 }
    ],
    autoheight: true,
    autowidth: true,
    data: tableData
});
</code>```

A complex class hierarchy and passing objects instead of strings:

```<code>var oTable = new sap.ui.table.Table({
    title: "Movies",
});

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Film title"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "title"),
    sortProperty: "title",
    filterProperty: "title",
    width: "200px"
}));

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Released"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "released"),
    sortProperty: "released",
    filterProperty: "released",
    width: "80px"
}));

oTable.addColumn(new sap.ui.table.Column({
    label: new sap.ui.commons.Label({text: "Votes"}),
    template: new sap.ui.commons.TextField().bindProperty("value", "votes"),
    sortProperty: "votes",
    filterProperty: "votes",
    width: "100px"
}));

// add the other columns...

var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: tableData});
oTable.setModel(oModel);
oTable.bindRows("/modelData");
</code>```

In both cases, tableData is a plain JSON array, so no differences there:

```<code>[
    { id: 1, title: "Shawshank Redemption", year: 1994, votes: 678790, rank: 1 },
    { id: 2, title: "The Godfather", year: 1972, votes: 511495, rank: 2 }
]
</code>```

What are the advantages and disadvantages of these two approaches, in terms of learning curve, maintainability, avoidance of antipatterns, reusability, and other software engineering best practices?


问:
RESTful Api: Send email with links to client URL
A client can call the following REST api URI to send an enquiry

```<code>POST /v1/businesses/{business_name}/enquiries
</code>```

The enquiry can then be viewed through the following call:

```<code>GET /v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a new enquiry is posted, the business is informed via email. The email includes a link to the enquiry. The issue I have is that the API will add the following link to email:

```<code>http://api.com/v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a user clicks the link in the email, they will be incorrectly taken to the API resource instead of the client page. So I need the email to contain the following link:

```<code>http://client.com/dashboard/{business_name}/enquiries/{enquiry_id}
</code>```

Noted: Above client URL is an example. Clients can implement their own routing however they want, a single page client app URL could also be used. The point is, the client URL must be exposed in the email, not the API URL.

I'm not quite sure how to get client URLs into the email.

One option would be to provide a client URL in the original POST request. Problem with this is that the client won't know the URL to use until after the POST, at which point the email has already been added to the queue.

Another option is to pull out the queueing of emails from the API and make the clients responsible for it. I don't really like this idea as client implementers will not be too happy that they purchased the API, only to then find out they then have to decide when to queue emails.

答:
How is the enquiry_id in the "client URL" (that points to a partner's site) generated? If it always matches the enquiry ID that is being used for the URLs you control, then you can simply require that the partners provide a URL template for you to use when setting up an integration with their system. When you generate the email, use the provided URL template to generate the partner URL.

By contrast, if the URL is completely generated by the partner, you need to add a step prior to sending the email: a call to the partner's API in order to determine the URL.

Whichever way, there is behavior that is necessary from both your application and the partner's application: they must provide a way for you to generate an URL for yourself (in which case you bear the responsibility for generating the URL and sending it), or they must provide a way for you to ask them to generate a URL (in which case you bear the responsibility for the API call and inserting the URL in the email).

This is a very typical integration scenario, by the way.

You may also consider whether the URL generation is different on a per-partner basis. If you are partnered with four companies, two might use standard URL templating while the other two require customized integrations to determine an URL. On an architectural level, this means that you will need to accommodate flexibility in this subystem:

Time to send an email.

Which partner is this email using?

How do I generate an URL for this partner?

Generate the URL.

Include the URL in the email.

Send the email.

A common approach to this would be to have an URLGeneratorFactory that returns a class implementing the interface URLGenerator; the identity of the partner determines which specific implementation is used.

I have written an example to clarify this answer.


问:
A practical use of "yield" keyword in C#
After almost 4 years of experience, I haven't seen a code where yield keyword is used. Can somebody show me a practical usage (along explanation) of this keyword, and if so, aren't there other ways easier to fullfill what it can do?

答:
Expanding upon Jan_V's answer, I just hit a real-world case related to it:

I needed to use the Kernel32 versions of FindFirstFile/FindNextFile.  You get a handle from the first call and feed it to all subsequent calls.  Wrap this in a enumerator and you get something you can directly use with foreach.


问:
Check a boolean before setting it in a loop, or just set it
I have a rather tight loop with the following check to see if balance had ever been positive:

```<code>balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance:
       balance_null = False
</code>```

In no place would balance_null ever be set back to True. Would the code be more efficient if I were to check the state of balance_null before setting it?

```<code>balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance and `balance_null`==True:
       balance_null = False
</code>```

The code example is in Python, but I am actually interested in the general case, which is why I'm not simply benchmarking it myself. What is considered a best practice, and what are the exceptions to the rule?

答: Setting a boolean variable is a vanishingly small cost in most programming languages.  Don't check it first to see if it's set; just set it.</p>


答:
If setting the boolean is the only reason for the loop then you may just as well break out of it when setting the boolean:

```<code>balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance:
       balance_null = False
       break;
</code>```

or extract the loop to a function and use early return.

Title: Check a boolean before setting it in a loop, or just set it

Body:
I have a rather tight loop with the following check to see if balance had ever been positive:

```<code>balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance:
       balance_null = False
</code>```

In no place would balance_null ever be set back to True. Would the code be more efficient if I were to check the state of balance_null before setting it?

```<code>balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance and `balance_null`==True:
       balance_null = False
</code>```

The code example is in Python, but I am actually interested in the general case, which is why I'm not simply benchmarking it myself. What is considered a best practice, and what are the exceptions to the rule?

Body:
If setting the boolean is the only reason for the loop then you may just as well break out of it when setting the boolean:

balance_null = True

while (crazy_loop()):
    ...
    if 0.0 < balance:
       balance_null = False
       break;

or extract the loop to a function and use early return.


答:
You shouldn't check it -- not because it is more expensive to do so (given todays cpu's that is by no means certain), but because it is conceptually unnecessary. Adding it makes the code harder to reason about.

All code should serve a purpose, when reading the code we not only interpret it, we also try to extract that purpose -- to understand both what it is doing, and why.

Code which serves no purpose is thus a hinderance.  It can cause considerable delays as a purpose is sought -- and of course not found.

If, in a specific case, you were to profile the code, find a significant performance impact, then you could add the check, with an appropriate comment (said comment to include compiler and version tested).


答:
As a user, I don't expect the whitespace on either side of the equals sign to change the value of the key or the value. See this related question on unix.SE as too how confusing the situation can be.

Don't make it harder on your users, trim whitespace from both the key and the value. If leading whitespace has a real use case for either, then let the user wrap the key or value in quotes.

Title: What is best practice to handle whitespaces when letting the user edit the configuration, the name=value pairs?

Body:
For instance, you let the user define the notorious path variable. How do you interpret apppath = C:\Program Files\App?

This looks like a programming language adopted practice to ignore the white spaces and you leave them around the equality mark for readability, but it might be a valid variable value with white space in the application (consider, it is a suffix).

Even keys can contain whitespaces, can't they?

What is the general best practice for my application? If I have:

```<code>key-example = value-example
</code>```

should I interpret the key being "key-example" or "key-example " and the value as being "value-example" or " value-example"?


问:
Software development - The industry & general trends / Bad practices
I am a Web Developer and part of a small team working on an abundance of projects. This is my first "actual" real company after graduating with a degree in computer Science and I have about 2 years Asp, SQL etc experience.

I'm going to try to get straight to the point here. First of a couple of things:

1) We NEVER comment code. "Commenting code is for the weak" are the exact words, and we can rather use that time we would've spend on inserting comments here and there on churning out more code.

2) We don't do documentation. "We are IT guys" and we don't need to document stuff, we remember it automatically.. (Not my words)

3) We NEVER have code reviews and or meetings. Thus anyone can commit anything to the SVN repository. We have such a lot of projects, the chances another developer will ever see your code is highly unlikely.

4) We don't do unit testing of any kind. We have "testers" which aren't dedicated testers, rather ambiguous department responsible for project management etc. They know the system really well so they can do front-end testing (usually done quickly).

5) We have a "If it builds ship it mentality". I get chills every time I have someone mention this. (Basically we don't care about code quality).

6) Discouraged from asking for help from senior developers, no mentor-ship. We work like machines. As long as you keep churning out code, your okay.

7) Some make code dynamic to the point where no-one can maintain it. No really.. Dynamic SQL inside dynamic SQL inside... 5000 line SQL queries. It literally comes to the point where nobody except the "genius" that wrote it can or wants to maintain it. Sure you want to make code as dynamic as possible, but still it should be maintainable? Or do I have it wrong here?

8) There are no specifications. But when you are asked to predict and make an estimate of how long it will take you to correct a "bug" or do something on a piece of code you've never seen before, you are expected to make an estimation "there and then" on the spot. 2 weeks, 1 day and 3 and a half hours... Nice..Usually ends up being totally incorrect, everyone misses their deadlines thus the business is unhappy.

We are so rushed to get bugs done on paper, that we rush it, commit bad untested code, do things poorly and digging a hole for the next poor soul who has to maintain it.

E.g. I did an enhancement a couple where I added rights for a user function. A couple of months down the line, in came another enhancement assigned to someone else. He actually saw that I already did it, and built another function which just "triggered" my code. Thus we had 2 completely identical functions with different wording. The bug to fix it came to me, and I had to sort out the code.

Another scenario. We started a redo of a project in MVC. Instead of properly researching and taking time to get to know MVC, the dev jumped in and started coding with SESSIONS and hard-coded controls etc instead of making use of html helpers. Layout pages, BundleConfigs and all other essential and basic parts were overlooked. Why didn't we do things properly?

My question:

Is this industry standard to rush things? Even if it means creating a handful more bugs and problems which will cost more time in future to fix? Instead of initially spending an hour or two extra and doing something properly, we have to come back to bug after bug in the end costing us lets say 10 hours of work. (Sure there will always be bugs), but it seems the guys getting the praise are the ones committing horrible code, and creating headaches for everyone. It seems there is little place for someone who take things a little slower and lays down a solid base.

Furthermore, is it industry standard not to do testing, comment code, create documentation etc.. ?

I am a little bit frustrated at this point, don't quite know where to look..

I would appreciate any comments or opinions.

EDIT:

I guess my question has been indirectly answered. I am curious as to the general industry and other companies? Are all companies geared this way? Is there light at the tunnel, if say you go work for a big player like Microsoft or Google? Do any companies out there still bother with unit testing, code reviews, other performance reviews or code quality practices? It seems the answer from the other articles is sadly no. So, how I want to distinguish my question from the other existing questions is, I want to know what does the grass look like on the other side? Other companies?

答: Look at it with the business eyes: either, this way of work is wrong, it means sooner or later the firm won't be able to find developers, or to hire enough of them to fix all the unmaintable code. Or, the code still generates enough money for the firm to survive. Therefore, there's nothing wrong.</p>


答:
Remember that .NET Framework BCL code is optimized for being useful to the largest number of programmers, not for good performance in your particular application.  So it's highly likely that you can beat the performance of any particular piece of it, even if you aren't a Rico Mariani.

However, you should learn from those experts, in particular mantras like "Measure, Measure, Measure".  This doesn't mean you have to build and debug your version completely before figuring out whether you can beat the BCL.  It does mean you identify which portions of the library code are causing you performance issues, so you don't waste effort re-inventing what doesn't matter.

Once you know how good or bad the performance of the general-purpose code is, you stand a good chance of predicting whether you'll be able to beat it.  Especially if you run some scalability tests.  There are lots of framework-provided widgets where simple operations like adding multiple listbox items1 have quadratic (or worse) complexity... simply because the largest number of applications never put more than two dozen items in the control anyway.  Armed with an estimate of the standard widget's runtime (and memory) complexity for the operations you need, you'll know exactly where you have the opportunity to do better in a way that pays dividends on your effort.

1 Sometimes the documentation points these out and even provides a way to plug in optimized-for-the-application code without throwing away the whole library component.  For example, ListView "virtual mode", or "Owner-Draw" for the tradition Win32 controls.

Title: Would redrawing controls in c# give more performance?

Body:
Now I realize this is a kind of weird question but here it is:
Let us assume I redraw all the controls by myself rather than using the default provided ones (Obviously I'm talking of winforms as WPF is already a custom drawn control set and winforms are just a way to access the Win32 API). Now I make an application with my custom-drawn controls. Then I make an application with winforms, which, in turn, uses the Win32 API. Now, when I run both the applications, will there be any performance difference? If yes, which will perform better?

Now comes the main question:
How (and based on what factor(s)) do you decide / predict as to which will perform better?

P.S. Forgive me if I am not clear enough. I always have trouble expressing my thoughts.

ContentLicense: CC BY-SA 4.0


问:
How to migrate my thinking from C++ to C#
I am an experienced C++ developer, I know the language in great details and have used some of its specific features intensively. Also, I know principles of OOD and design patterns. I am now learning C# but I cannot stop the feeling not being able to get rid of C++ mindset. I tied myself so hard to the strengths of C++ that I cannot live without some of the features. And I cannot find any good workarounds or replacements for them in C#.

What good practices, design patterns, idioms that are different in C# from C++ perspective can you suggest? How to get a perfect C++ design not looking dumb in C#?

Specifically, I cannot find a good C#-ish way to deal with (recent examples):

Controlling the lifetime of resources that require deterministic cleanup (like files). This is easy having using in hand but how to use it properly when ownership of the resource is being transfered [... betwen threads]? In C++ I would simply use shared pointers and let it take care of 'garbage collection' just at the right time.

Constant struggling with overriding functions for specific generics (I love things like partial template specialization in C++). Should I just abandon any attempts to do any generic programming in C#? Maybe generics are limited on purpose and it is not C#-ish to use them except for a specific domain of problems?

Macro-like functionality. While generally a bad idea, for some domain of problems there is no other workaround (e.g. conditional evaluation of a statement, like with logs that should only go to Debug releases). Not having them means that I need to put more if (condition) {...} boilerplate and it is still not equal in terms of triggering side effects.

答:
As far as I can see, the only thing allowing for deterministic Lifetime Management is IDisposable, which breaks down (as in: no language or type system support) when, as you noticed, you need to Transfer Ownership of such a resource.

Being in the same boat as you -- C++ developer doing C# atm. -- the lack of support to model Ownership Transfer (files, db-connections, ...) in the C# types/signatures has been very annoying to me, but I have to admit that it does work quite OK to "just" rely on convention and API docs to get this right.

Use IDisposable to do deterministic clean up iff necessary.

When you need to transfer ownership of an IDisposable, just make sure the API involved is clear on this and don't use using in this case, because using can't be "cancelled" so to speak.

Yes, it's not as elegant as what you can express in the type system with modern C++ (move sematics, etc.), but it get's the job done, and (amazingly to me) the C# community as a whole doesn't seem to care overmuch, AFAICT.


答:
Is this industry standard to rush things?

To some degree. Companies are in business to make money, and (almost universally) business people want things faster - even at the expense of some hand-wavy quality.

Furthermore, is it industry standard not to do testing, comment code, create documentation etc.. ?

At my current company, we have no QA department. I've heard of a few others recently that also do not. There are a number of arguments. Having a QA department means that developers are more likely to overlook quality since it's "not their job". Having a QA department is too costly for the number of bugs they find. Dedicated QA people are largely horrible, so why bother?

It's decidedly debatable if that is a good idea. It is certainly not standard.

"Commenting code is for the weak" are the exact words, and we can rather use that time we would've spend on inserting comments here and there on churning out more code.

What sort of comments do you expect? Certainly some well placed comments are good, but javadoc style comments are increasingly uncommon. Comments won't help if your class/function/variable has a bad name. If you have good names, comments are duplicated effort. If you have bad names, comments do nothing but waste time better spent on fixing your names.

"We are IT guys" and we don't need to document stuff, we remember it automatically..

While I disagree with the reason, documentation is decidedly uncommon in many industries for good reason. It's costly to create. It is invariably out of date or incorrect. And you often need to duplicate it for various target audiences.

We NEVER have code reviews and or meetings.

Almost all industries will have some meetings. Code reviews are less common, but maybe not as necessary as you might imagine. I've worked in a few places that require code reviews, and probably 75% of the time, they're completely worthless. Process for the sake of process. And that's at places that do code reviews well. If you don't have the skill/patience/communication to do code reviews rather than nitpicking useless stuff or taking turns criticizing each other...

We have a "If it builds ship it mentality"

Awesome. This is fairly common these days since gated check-ins and automated test suites can provide high confidence that building code is working code. ...though it doesn't sounds as though you have that sort of infrastructure.

There are no specifications.

Sadly, also common. If you're doing agile well, then your specification is the code, which you build up day by day and week by week working closely with your stakeholders. More often, it's an excuse for business people to not do their jobs.

That said, your argument about estimates is fishy. What makes you think that specifications will make your estimates better? They're likely to change anyways...

So what you describe sounds like a crappy, non-standard, dysfunctional environment taken together - one that expects people to pump out crappy code with no long term view. But in isolation, some of the things you have problems with aren't so much problems if done well, or not the cause of badness you see. And even this sort of short term coding view can be viable in businesses where the code will be thrown away, and/or time to market actually matters (which is far, far less than business people think it is).

Title: Software development - The industry & general trends / Bad practices

Body:
I am a Web Developer and part of a small team working on an abundance of projects. This is my first "actual" real company after graduating with a degree in computer Science and I have about 2 years Asp, SQL etc experience.

I'm going to try to get straight to the point here. First of a couple of things:

1) We NEVER comment code. "Commenting code is for the weak" are the exact words, and we can rather use that time we would've spend on inserting comments here and there on churning out more code.

2) We don't do documentation. "We are IT guys" and we don't need to document stuff, we remember it automatically.. (Not my words)

3) We NEVER have code reviews and or meetings. Thus anyone can commit anything to the SVN repository. We have such a lot of projects, the chances another developer will ever see your code is highly unlikely.

4) We don't do unit testing of any kind. We have "testers" which aren't dedicated testers, rather ambiguous department responsible for project management etc. They know the system really well so they can do front-end testing (usually done quickly).

5) We have a "If it builds ship it mentality". I get chills every time I have someone mention this. (Basically we don't care about code quality).

6) Discouraged from asking for help from senior developers, no mentor-ship. We work like machines. As long as you keep churning out code, your okay.

7) Some make code dynamic to the point where no-one can maintain it. No really.. Dynamic SQL inside dynamic SQL inside... 5000 line SQL queries. It literally comes to the point where nobody except the "genius" that wrote it can or wants to maintain it. Sure you want to make code as dynamic as possible, but still it should be maintainable? Or do I have it wrong here?

8) There are no specifications. But when you are asked to predict and make an estimate of how long it will take you to correct a "bug" or do something on a piece of code you've never seen before, you are expected to make an estimation "there and then" on the spot. 2 weeks, 1 day and 3 and a half hours... Nice..Usually ends up being totally incorrect, everyone misses their deadlines thus the business is unhappy.

We are so rushed to get bugs done on paper, that we rush it, commit bad untested code, do things poorly and digging a hole for the next poor soul who has to maintain it.

E.g. I did an enhancement a couple where I added rights for a user function. A couple of months down the line, in came another enhancement assigned to someone else. He actually saw that I already did it, and built another function which just "triggered" my code. Thus we had 2 completely identical functions with different wording. The bug to fix it came to me, and I had to sort out the code.

Another scenario. We started a redo of a project in MVC. Instead of properly researching and taking time to get to know MVC, the dev jumped in and started coding with SESSIONS and hard-coded controls etc instead of making use of html helpers. Layout pages, BundleConfigs and all other essential and basic parts were overlooked. Why didn't we do things properly?

My question:

Is this industry standard to rush things? Even if it means creating a handful more bugs and problems which will cost more time in future to fix? Instead of initially spending an hour or two extra and doing something properly, we have to come back to bug after bug in the end costing us lets say 10 hours of work. (Sure there will always be bugs), but it seems the guys getting the praise are the ones committing horrible code, and creating headaches for everyone. It seems there is little place for someone who take things a little slower and lays down a solid base.

Furthermore, is it industry standard not to do testing, comment code, create documentation etc.. ?

I am a little bit frustrated at this point, don't quite know where to look..

I would appreciate any comments or opinions.

EDIT:

I guess my question has been indirectly answered. I am curious as to the general industry and other companies? Are all companies geared this way? Is there light at the tunnel, if say you go work for a big player like Microsoft or Google? Do any companies out there still bother with unit testing, code reviews, other performance reviews or code quality practices? It seems the answer from the other articles is sadly no. So, how I want to distinguish my question from the other existing questions is, I want to know what does the grass look like on the other side? Other companies?


问:
Iterating a function with a static argument: Global functions + lambdas vs internal function?
I am never sure which of these is better form:

Option A

```<code>def a(x,y):
  def b(z): return z+y
  return map(b, x)
print a([10,20], 5)
</code>```

Option B

```<code>def b(z,y): return z+y
def a(x,y):
  return map(lambda x: b(x,y), x)
print a([10,20], 5)
</code>```

Suppose that b() is ONLY ever called from inside a().

I know Option B is more efficient because it only declares b() once, and then the variable y is just passed as a context variable. But Option A seems to be simpler syntax, eliminating the need to construct a lambda, and simplifying the interface of b(). Suppose further that there could actually be many context arguments. The complexity blows up on the interface of b():

Option A2:

```<code>def a(x,y1,y2,y3,y4,y5):
  def b(z): return z+y1+y2+y3+y4+y5
  return map(b, x)
print a([10,20], 5,6,7,8,9)
</code>```

Option B2:

```<code>def b(z,y1,y2,y3,y4,y5): return z+y1+y2+y3+y4+y5
def a(x,y1,y2,y3,y4,y5):
  return map(lambda x: b(x,y1,y2,y3,y4,y5), x)
print a([10,20], 5,6,7,8,9)
</code>```

Option A2 is far fewer characters.
Thoughts?

答:
Do you need the efficiency more than the simplicity, or the simplicity more than the efficiency?

Use what makes sense for your specific application.  If you need the simplicity more than the efficiency, then use option A.  If you need the efficiency more than the simplicity, then use option B.

Code profilers can help immensely in this regard.  Programmers are notoriously bad at guessing how expensive a given operation is; a code profiler can give you evidence that will help you determine the real cost of a computation, and help you make a better, more informed choice.


答:
Per the Zen of Python: simple is always better than complex. I'd pick the first option on the principle that it is vastly easier to understand and thus easier to maintain. Generally speaking, in Python, one worries more about the ease of use of the code than the efficiency of the code.

If you want to simplify long lists of arguments, use *args:

4.7.3. Arbitrary Argument Lists

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

```<code>def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))
</code>```

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.

```<code>>>> def concat(*args, sep="/"):
...    return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
</code>```

Title: Iterating a function with a static argument: Global functions + lambdas vs internal function?

Body:
I am never sure which of these is better form:

Option A

```<code>def a(x,y):
  def b(z): return z+y
  return map(b, x)
print a([10,20], 5)
</code>```

Option B

```<code>def b(z,y): return z+y
def a(x,y):
  return map(lambda x: b(x,y), x)
print a([10,20], 5)
</code>```

Suppose that b() is ONLY ever called from inside a().

I know Option B is more efficient because it only declares b() once, and then the variable y is just passed as a context variable. But Option A seems to be simpler syntax, eliminating the need to construct a lambda, and simplifying the interface of b(). Suppose further that there could actually be many context arguments. The complexity blows up on the interface of b():

Option A2:

```<code>def a(x,y1,y2,y3,y4,y5):
  def b(z): return z+y1+y2+y3+y4+y5
  return map(b, x)
print a([10,20], 5,6,7,8,9)
</code>```

Option B2:

```<code>def b(z,y1,y2,y3,y4,y5): return z+y1+y2+y3+y4+y5
def a(x,y1,y2,y3,y4,y5):
  return map(lambda x: b(x,y1,y2,y3,y4,y5), x)
print a([10,20], 5,6,7,8,9)
</code>```

Option A2 is far fewer characters.
Thoughts?

Body:
Per the Zen of Python: simple is always better than complex. I'd pick the first option on the principle that it is vastly easier to understand and thus easier to maintain. Generally speaking, in Python, one worries more about the ease of use of the code than the efficiency of the code.

If you want to simplify long lists of arguments, use *args:

4.7.3. Arbitrary Argument Lists

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.

>>> def concat(*args, sep="/"):
...    return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'


问:
How to make scalable modules in a div element
I'm interested in creating web modules that are encapsulated by a div element in a manner that, by simply resizing the div, everything in that div scales to the dimensions of that div proportionately (fonts, sub-divs, etc.).

A couple of weeks ago, I made this form that scales pretty well as you resize the page. I was able to achieve this by sizing things with the CSS3 viewport relative sizing units.

These viewport units work great if your module is the size of the entire viewport (the size of the whole page), but these same units don't work if your intended "viewport" is going to be just a div that is only one part of an entire web page and a div you intend to reuse in multiple pages with total different "surroundings".

Conceptually, the idea is to be able to create reusable modules that can be placed anywhere inside of any webpage, and by simply setting the modules div container size, all contents scale proportionately based on the size of the div.

I want to create modules that can be consumed by any webmaster, and all the webmaster has to do is set the height, width and location of the module, and the module scales perfectly to the webmaster's desired dimensions.

Any advice toward this concept would be appreciated.

答:
Set the div's style to position: absolute or position: relative.

Set the div's children to position: absolute.

Position the children using % dimensions.

Example (http://jsfiddle.net/o697zdeg/):

```<code><div style="position: relative; border: 5px solid red; width: 100px; height: 100px">
    <div style="position: absolute; top: 0; bottom: 0; width: 50%; background-color: blue"></div>
    <div style="position: absolute; top: 0; bottom: 0; width: 50%; right: 0; background-color: green"></div>
</div>
</code>```

Body:
Set the div's style to position: absolute or position: relative.

Set the div's children to position: absolute.

Position the children using % dimensions.

Example (http://jsfiddle.net/o697zdeg/):

<div style="position: relative; border: 5px solid red; width: 100px; height: 100px">
    <div style="position: absolute; top: 0; bottom: 0; width: 50%; background-color: blue"></div>
    <div style="position: absolute; top: 0; bottom: 0; width: 50%; right: 0; background-color: green"></div>
</div>


问:
Where should I put bindings for dependency injection?
I'm new to dependency injection and though I've really liked it so far, I'm not sure where bindings should go. I'm using Guice in Java, so some of what I say might be specific to just Guice. As I see it, there's two options:

Accompanying the class(s) its needed for. Then, just write install(OtherClassModule.class) in whatever other modules want to be able to use said class. As I see it, the advantage of this is that classes that want to use it (or manage classes that want to use it) don't need to know any of the implementation detail. The issue I see is that what if two classes want to use two different versions of the same class? There's a lot of customization possible because of DI and this seems to restrict it a lot.

Implemented in the module of the class(s) its needed for. It's the flip of what I said above. Now you have customization, but not encapsulation.

Is there a third option? Am I misunderstanding something obvious? What's the best practice?

答:
Mark Seemann has written extensively about this topic. Here's a summary of his points.

For maximum reuse, structure your code as one or more libraries and/or frameworks which do not require or even mention a particular IoC container, and an application whose sole job is to create concrete instances and introduce them to each other (aka the Composition Root). A Composition Root may encapsulate an IoC container, or it may simply use new-expressions. Composition Roots are not meant to be reusable.

It should be straightforward to use a library or a framework without also installing an IoC container.

Use constructor injection to make libraries Dependency-Injection-friendly, though for convenience you can supply some creation methods which hard-code common dependencies. These creation methods should use new-expressions, not an IoC framework.

Use abstract factories to make frameworks Dependency-Injection friendly. For example, a web framework may need a way to create request handlers. By relying upon an interface for that operation, frameworks allow applications to customise the creation of handlers without requiring the use of a particular container.

So to answer your question directly: don't define any Guice bindings for your library. You shouldn't make your clients depend on a particular framework. If you want to provide a way to create objects with the "normal" set of dependencies filled-in, use new-expressions encapsulated inside creation methods or builders.


问:
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

答:
I'd go for the simplest and easiest solution which will cover your current requirement.

As you mentioned all you need is to remove couple of fields, json manipulation is enough and it's very simple.

In future, as you believe if it comes to more complex transformations (which are not easy to do with json manipulation) you can easily add DTOs in middle and do the transformations. Since you are getting json and sending back json adding DTOs won't affect any of the external systems.


问:
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 answer depends on your domain and persistent framework.

For example, list of Prizes seems to be essential part of the user, however if a given user has a lot of Prizes, and if you are using eager loading this design would be an issue as it would affect the performance, However if you use lazy loading this would not be an issue, as it would not actually fetch these data if you just want to access user's data such as FirstName and LastName.