问:
How to model users accounts in ASP MVC Framework with Entity Framework using code-first approach?
How do you design your code-first approach in entity framework when your code should include user data (name, password...) without repeating/overwriting what the MVC framework will generate in terms of user tables, classes, authorization and authentication

As simple example, if i have an application that will manage user projects, my models will contain the following classes, and have the following relationship:

```<code>- One user may be assigned one or MANY projects
- One project may be assigned to one or MANY users
</code>```

( just to show the many to many ERD relationship nature)

```<code>class User{
    //implementation of the class members and
    // navigation properties to alow Entity Framework to create the DB tables
}

class Project{
    //implementation of the class members and
    // navigation properties to alow Entity Framework to create the DB tables
}
</code>```

Now the problem i am facing is that EF and ASP .net MVC framework takes care of creating user tables, profiles and roles entities...

I am not sure whether it is possible to design my classes in a way to show an automatic (conventional)  relationship with the rest of the tables created by MVC.

In the case this needs to be done by writting custom Authentication classes, can you please explain how? because i have found many articles that discuss the same issue but without pointing out the relationship between the project classes and the MVC created classes / tables, plus  if the developer choses to use the MVC way he will end up with two data contexts, even after merging both tables in one sql server catalog.

答:
Here is how you can accomplish this.

I am going to explain a way in which you can utilize existed Asp.Net Mvc Accounts Tables even plus you can add further into them as well as per your requirements.

First you need to install following Packages.

```<code>Install-Package Microsoft.AspNet.Identity
  Install-Package Microsoft.AspNet.Identity.EntityFramework
</code>```

Now you would have to do further as follows.

First Of All Asp.Net Identity provides a table IdentityUser which contains following properties

Id,UserName,PasswordHash,SecurityStamp,Discriminator

Suppose I want to add further properties to i can do that by Creating a class
and Inheriting it from IdentityUser

Here is example lets say I call it Client.

```<code>public class Client:IdentityUser
{

      //Suppose I want to add Further Properties to to my IdentityUser
      //table provided by Asp.Net by default.
      //suppose i want Email,Date Birth.

   [Required]
   [Display(Name = "Email")]
   public string Email { get; set; }

   [Required]
   [Display(Name = "BirthDate")]
   public DateTime BirthDate { get; set; }

}

Now Create Your Model classes Lets say in my case One User can have many Projects.

 public class Project
  {

 //Now all your properties will go here
   // plus now you can connect projects to IdentityUser
   //by using Client class which is inherited from IdentityUser.

        public virtual Client Client{get; set;}

   }
</code>```

Your further model classes will go here.

```<code>public class  SecondModelClass
   {

   }

Now Go to your context rather than inheriting it from DbContext you can inherit it from  IdentityDbContext   here is sample code below.

//Notice I am passing it Client class which was inherited from IdentityUser

public class YourContextName:IdentityDbContext<Client>
{

    public YourContextName():base("connectionStringName")
    {

    }

    public class IdentityUserLoginConfiguration :      EntityTypeConfiguration<IdentityUserLogin>
    {
        public IdentityUserLoginConfiguration()
        {
            HasKey(iul => iul.UserId);
        }
    }

    public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
    {
        public IdentityUserRoleConfiguration()
        {
            HasKey(iur => iur.RoleId);
        }

    }

    public DbSet<Project> Projects { get; set; }

    public DbSet<ModelClass2> AnyName { get; set; }

    public DbSet<ModelClass3> MoreClassesName { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
        modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    }

}
</code>```

Now it you entire AccountController you would have to pass   your Client class inherited from IdentityUser

```<code>public class AccountController : Controller
{
    public AccountController()
        : this(new UserManager<Client>(new UserStore<Client>(new Context.YourContextName())))
    {
    }

    public AccountController(UserManager<Client> userManager)
    {
        UserManager = userManager;
    }

    public UserManager<Client> UserManager { get; private set; }

  //Further Code Will go below here........................
  //

}
</code>```

This solution will utilize everything provided by Asp.Net Identity plus Your customization as well.

Cheers.

Body:
Here is how you can accomplish this.

I am going to explain a way in which you can utilize existed Asp.Net Mvc Accounts Tables even plus you can add further into them as well as per your requirements.

First you need to install following Packages.

Install-Package Microsoft.AspNet.Identity
  Install-Package Microsoft.AspNet.Identity.EntityFramework

Now you would have to do further as follows.

First Of All Asp.Net Identity provides a table IdentityUser which contains following properties

Id,UserName,PasswordHash,SecurityStamp,Discriminator

Suppose I want to add further properties to i can do that by Creating a class
and Inheriting it from IdentityUser

Here is example lets say I call it Client.

public class Client:IdentityUser
{

      //Suppose I want to add Further Properties to to my IdentityUser
      //table provided by Asp.Net by default.
      //suppose i want Email,Date Birth.

   [Required]
   [Display(Name = "Email")]
   public string Email { get; set; }

   [Required]
   [Display(Name = "BirthDate")]
   public DateTime BirthDate { get; set; }

}

Now Create Your Model classes Lets say in my case One User can have many Projects.

 public class Project
  {

 //Now all your properties will go here
   // plus now you can connect projects to IdentityUser
   //by using Client class which is inherited from IdentityUser.

        public virtual Client Client{get; set;}

   }

Your further model classes will go here.

public class  SecondModelClass
   {

   }

Now Go to your context rather than inheriting it from DbContext you can inherit it from  IdentityDbContext   here is sample code below.

//Notice I am passing it Client class which was inherited from IdentityUser

public class YourContextName:IdentityDbContext<Client>
{

    public YourContextName():base("connectionStringName")
    {

    }

    public class IdentityUserLoginConfiguration :      EntityTypeConfiguration<IdentityUserLogin>
    {
        public IdentityUserLoginConfiguration()
        {
            HasKey(iul => iul.UserId);
        }
    }

    public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
    {
        public IdentityUserRoleConfiguration()
        {
            HasKey(iur => iur.RoleId);
        }

    }

    public DbSet<Project> Projects { get; set; }

    public DbSet<ModelClass2> AnyName { get; set; }

    public DbSet<ModelClass3> MoreClassesName { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
        modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    }

}

Now it you entire AccountController you would have to pass   your Client class inherited from IdentityUser

public class AccountController : Controller
{
    public AccountController()
        : this(new UserManager<Client>(new UserStore<Client>(new Context.YourContextName())))
    {
    }

    public AccountController(UserManager<Client> userManager)
    {
        UserManager = userManager;
    }

    public UserManager<Client> UserManager { get; private set; }

  //Further Code Will go below here........................
  //

}

This solution will utilize everything provided by Asp.Net Identity plus Your customization as well.

Cheers.


问:
Do else blocks increase code complexity?
Here is a very simplified example. This isn't necessarily a language-specific question, and I ask that you ignore the many other ways the function can be written, and changes that can be made to it.. Color is of a unique type

```<code>string CanLeaveWithoutUmbrella()
{
    if(sky.Color.Equals(Color.Blue))
    {
        return "Yes you can";
    }
    else
    {
        return "No you can't";
    }
}
</code>```

A lot of people I've met, ReSharper, and this guy (whose comment reminded me I've been looking to ask this for a while) would recommend refactoring the code to remove the else block leaving this:

(I can't recall what the majority have said, I might not have asked this otherwise)

```<code>string CanLeaveWithoutUmbrella()
{
    if(sky.Color.Equals(Color.Blue))
    {
        return "Yes you can";
    }
    return "No you can't";
}
</code>```

Question: Is there an increase in complexity introduced by not including the else block?

I'm under the impression the else more directly states intent, by stating the fact that the code in both blocks is directly related.

Additionally I find that I can prevent subtle mistakes in logic, especially after modifications to code at a later date.

Take this variation of my simplified example (Ignoring the fact the or operator since this is a purposely simplified example):

```<code>bool CanLeaveWithoutUmbrella()
{
    if(sky.Color != Color.Blue)
    {
        return false;
    }
    return true;
}
</code>```

Someone can now add a new if block based on a condition after the first example without immediately correctly recognizing the first condition is placing a constraint on their own condition.

If an else block were present, whoever added the new condition would be forced to go move the contents of the else block (and if somehow they gloss over it heuristics will show the code is unreachable, which it does not in the case of one if constraining another).

Of course there are other ways the specific example should be defined anyways, all of which prevent that situation, but it's just an example.

The length of the example I gave may skew the visual aspect of this, so assume that space taken up to the brackets is relatively insignificant to the rest of the method.

I forgot to mention a case in which I agree with the omission of an else block, and is when using an if block to apply a constraint that must be logically satisfied for all following code, such as a null-check (or any other guards).

答:
Although the if-else case described has the greater complexity, in most (but not all) practical situations it does not matter much.

Years ago when I was working on software that was used for the aviation industry (it had to go through a certification process), yours was a question that came up.  It turned out that there was a financial cost to that 'else' statement as it increased the code complexity.

Here's why.

The presence of the 'else' created an implicit 3rd case that had to be evaluated--that of neither the 'if' nor the 'else' being taken.  You might be thinking (like I was at the time) WTF?

The explanation went like this ...

From a logical standpoint, there are only the two options--the 'if' and the 'else'.  However, what we were certifying was the object file the compiler was generating.  Therefore, when there was an 'else', an analysis had to be done to confirm that the generated branching code was correct and that a mysterious 3rd path did not appear.

Contrast this to the case where there is only an 'if' and no 'else'.  In that case, there are only two options--the 'if' path and the 'non-if' path.  Two cases to evaluate is less complex than three.

Hope this helps.

ContentLicense: CC BY-SA 3.0


问:
Converting our Windows Software to the web
We're looking at converting a software package from Windows over to the browser. It's a back office system consisting of Ledgers, Stock Control, Order Processing, etc and it's written in a legacy language (Dataflex).

The project consists of 200+ database tables, 100+ reports, 300+ Views, 100+ Dialog boxes and 200 or so Selection Lists.

I'm really struggling to get my head around the technologies that I'll need to use to convert this to a more modern web based programming language / framework. Even simple screens (Entering a stock location) seems overly complex. With the current language, I can drag a bunch of Fields to a form (a-la VB), wire in a tiny bit of database code and I've got a screen that'll allow me to find, delete, edit and change records easily. 10 minutes of development, tops.

Has anyone got any suggestions on how I can move from my current VB style programming language to one that allows similar functionality on the web?

Has anyone got any ideas how I go about working out how many man hours it's going to take to convert this sort of project to a new language on the web?

What Web Framework options are available, and how do I decide between going with something like Rails vs going with something like ASP.Net?

We've a tonne of code wired to OnClick and OnChange events. (I know this is bad). What strategies can I take with regard to converting this to the web?

I'll admit - I'm hopelessly confused by some of the newer syntaxes used by modern languages. Is there any language that allows me access to the database without having to subclass everything through IEnumerable and various weird Typecasting things.

Has anyone done anything like what we want to do? What were the pitfalls?

Sorry about the vagueness of the question. I'd be more specific but don't know where to start. Delete away if I'm asking the wrong thing or in the wrong place.

答:
Before you even start doing this:

"We're looking at converting a software package from Windows over to the browser. It's a back office system consisting of Ledgers, Stock Control, Order Processing, etc and it's written in a legacy language (Dataflex)."

Ask, and have a good answer to the simple question: WHY do you want to do this?

Is it nice to have?
Is it essential?
Is it so you can make revenue?
Is it because somebody thought it would be a neat idea?

You are about to embark on a massive software development task; which will as these things do, introduce new defects as well as cause a change of processes.

So some supplementary questions:

Are you, or is your organisation, prepared for the cost (in terms of development effort, diverted staff, defect fixing, disruption, etc)?

Are you prepared to have parallel running? (If not you have to cut over at some time and at that time the NEW needs to work. Really work. Not be debugged after cutover.)

Do you have to do data migration? (On a stock / inventory system, I bet you do. Otherwise there will be re-entering of existing data.)

Can you just go an buy something? Or rent? There are such systems available now as a service, just pay a monthly fee.

ContentLicense: CC BY-SA 2.5


问:
Null checking whilst navigating object hierarchies
I had to implement some code which traversed a small object hierarchy to fetch a value and display it in a TextView object (this is Android / Java). I had to do this 6 times to populate 6 TextViews for various values in the object hierarchy.

My implementation was Implementation B. But upon review, my colleague disagreed and certain that Implementation A was the way to go. I believe that my version is not just cleaner, but also less error prone as I could easily miss something as a developer.

Could you provide me with your opinion, with pros and cons for both of these implementations?

Implementation A:

```<code>if (house != null && house.getLounge() != null && house.getLounge().getLetter() != null)
{
    String myValue = house.getLounge().getLetter();
    textView.setText(myValue);
}
else
{
    // Do nothing, or maybe make textView hidden.
}
</code>```

Implementation B:

```<code>try
{
    String myValue = house.getLounge().getLetter();
    textView.setText(myValue);
}
catch (NullPointerException e)
{
    // Do nothing, or maybe make textView hidden.
}
</code>```

答:
Advantage of A:

You make clear, under what condition you want to do something:

```<code>house != null && house.getLounge() != null && house.getLounge().getLetter() != null
</code>```

That is the condition.
And you want to get a value and set another value.

```<code>String myValue = house.getLounge().getLetter();
textView.setText(myValue);
</code>```

So in terms of communicating intent, this is clear.
Btw. the second condition isn't necessary. If a String is null, nothing should be displayed.

Why B is wrong:

With try-catch you communicate: »I want to do x, which is somehow dangerous« - which it really isn't.
Your intent isn't as clear as under A.
And - in my eyes worse - you obscure an error-possibility:

```<code>String myValue = house.getLounge().getLetter();
textView.setText(myValue);
</code>```

A NullPointerException is thrown a) when getLounge() returns null and b) when textView is null. Since you are catching one NPE, you do not know which one.
Of course in such a simple case it should be easy to debug, but in general this is the wrong way.

I am in favour of a third way:

```<code>String myValue = (house.getLounge()!=null)?house.getLounge().getLetter:"";
</code>```

Of course, there is Diskussion about the usage of the ternary Operator (some languages abandoned the concept), but in this case it fits best: you are able to write a clean oneliner, which provides a default.

Body:
Advantage of A:

You make clear, under what condition you want to do something:

house != null && house.getLounge() != null && house.getLounge().getLetter() != null

That is the condition.
And you want to get a value and set another value.

String myValue = house.getLounge().getLetter();
textView.setText(myValue);

So in terms of communicating intent, this is clear.
Btw. the second condition isn't necessary. If a String is null, nothing should be displayed.

Why B is wrong:

With try-catch you communicate: »I want to do x, which is somehow dangerous« - which it really isn't.
Your intent isn't as clear as under A.
And - in my eyes worse - you obscure an error-possibility:

String myValue = house.getLounge().getLetter();
textView.setText(myValue);

A NullPointerException is thrown a) when getLounge() returns null and b) when textView is null. Since you are catching one NPE, you do not know which one.
Of course in such a simple case it should be easy to debug, but in general this is the wrong way.

I am in favour of a third way:

String myValue = (house.getLounge()!=null)?house.getLounge().getLetter:"";

Of course, there is Diskussion about the usage of the ternary Operator (some languages abandoned the concept), but in this case it fits best: you are able to write a clean oneliner, which provides a default.


问:
What is a good generalization of web development architecture?
I'm new to web development. From looking at popular open-source frameworks for both front-end and back-end, I have a general idea of what the modern full-stack web setup looks like:

Database <-> Back-end language ~ REST API <-> Front-end

Notes:

The back-end language (Python, Ruby, PHP, Java) generates the API, which is the only layer between the back and the front. The API has authentication to protect private data.

The front-end sends GET and POST requests to the API. A MVC framework can be used, such as Backbone, Angular, or Ember.js.

Is my understanding accurate?

答:
Your understanding is correct at high level.

Frontend mvc - angular, backbone, ember - however you need to host that on web server like apache, nodejs, etc which will help you held the static assets (CSS, images, JavaScript,etc)

Rest API - can leverage framework such as drop wizard, etc

Backend mvc - using spring, struts, etc to build the business logic which connects with rest API and the database drivers

The rest API approach would help you utilize service oriented architecture which can further be reused if you feel to go towards mobile apps.


答:
I noticed, changing my mind on this case.

When asked this question about a year ago, I would have answered something like:

»There should be only one entryand one exit to a method« And with this in mind, I would have suggested to refactor the code to:

```<code>bool CanLeaveWithoutUmbrella()
{
    bool result

    if(sky.Color == Color.Blue)
    {
        result = true;
    }
    else
    {
        result = false;
    }

    return result;
}
</code>```

From a communication viewpoint it is clear, what should be done. If something is the case, manipulate the result in one way, else manipulate it in another way.

But this involves an unnecessary else. The else expresses the default-case.
So in a second step, I could refactor it to

```<code>bool CanLeaveWithoutUmbrella()
{
    bool result=false

    if(sky.Color == Color.Blue)
    {
        result = true;
    }
    return result;
}
</code>```

Then the question raises: Why using a temporary variable at all?
The next step of refactorization leads to:

```<code>bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue)
    {
        return true;
    }
    return false;
}
</code>```

So this is clear in what it does. I would even go one step further:

```<code>bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue) return true;
    return false;
}
</code>```

Or for the faint-hearted:

```<code>bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue) { return true; }
    return false;
}
</code>```

You could read it like that:
» CanLeaveWithoutUmbrella returns a bool. If nothing special happens, it returns false« This is the first read, from top to bottom.

And then you "parse" the condition »If the condition is met, it returns true«
You could completely skip the conditional and have understood, what this function does in the default-case. Your eye and mind only have to skim through some letters on the left side, without reading the part on the right.

I'm under the impression the else more directly states intent, by stating the fact that the code in both blocks is directly related.

Yes, that is right. But that information is redundant. You have a default case and one "exception" which is covered by the if-statement.

When dealing with complexer structures, I would choose another strategy, omitting the if or it's ugly brother switch at all.

Title: Do else blocks increase code complexity?

Body:
Here is a very simplified example. This isn't necessarily a language-specific question, and I ask that you ignore the many other ways the function can be written, and changes that can be made to it.. Color is of a unique type

```<code>string CanLeaveWithoutUmbrella()
{
    if(sky.Color.Equals(Color.Blue))
    {
        return "Yes you can";
    }
    else
    {
        return "No you can't";
    }
}
</code>```

A lot of people I've met, ReSharper, and this guy (whose comment reminded me I've been looking to ask this for a while) would recommend refactoring the code to remove the else block leaving this:

(I can't recall what the majority have said, I might not have asked this otherwise)

```<code>string CanLeaveWithoutUmbrella()
{
    if(sky.Color.Equals(Color.Blue))
    {
        return "Yes you can";
    }
    return "No you can't";
}
</code>```

Question: Is there an increase in complexity introduced by not including the else block?

I'm under the impression the else more directly states intent, by stating the fact that the code in both blocks is directly related.

Additionally I find that I can prevent subtle mistakes in logic, especially after modifications to code at a later date.

Take this variation of my simplified example (Ignoring the fact the or operator since this is a purposely simplified example):

```<code>bool CanLeaveWithoutUmbrella()
{
    if(sky.Color != Color.Blue)
    {
        return false;
    }
    return true;
}
</code>```

Someone can now add a new if block based on a condition after the first example without immediately correctly recognizing the first condition is placing a constraint on their own condition.

If an else block were present, whoever added the new condition would be forced to go move the contents of the else block (and if somehow they gloss over it heuristics will show the code is unreachable, which it does not in the case of one if constraining another).

Of course there are other ways the specific example should be defined anyways, all of which prevent that situation, but it's just an example.

The length of the example I gave may skew the visual aspect of this, so assume that space taken up to the brackets is relatively insignificant to the rest of the method.

I forgot to mention a case in which I agree with the omission of an else block, and is when using an if block to apply a constraint that must be logically satisfied for all following code, such as a null-check (or any other guards).

Body:
I noticed, changing my mind on this case.

When asked this question about a year ago, I would have answered something like:

»There should be only one entryand one exit to a method« And with this in mind, I would have suggested to refactor the code to:

bool CanLeaveWithoutUmbrella()
{
    bool result

    if(sky.Color == Color.Blue)
    {
        result = true;
    }
    else
    {
        result = false;
    }

    return result;
}

From a communication viewpoint it is clear, what should be done. If something is the case, manipulate the result in one way, else manipulate it in another way.

But this involves an unnecessary else. The else expresses the default-case.
So in a second step, I could refactor it to

bool CanLeaveWithoutUmbrella()
{
    bool result=false

    if(sky.Color == Color.Blue)
    {
        result = true;
    }
    return result;
}

Then the question raises: Why using a temporary variable at all?
The next step of refactorization leads to:

bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue)
    {
        return true;
    }
    return false;
}

So this is clear in what it does. I would even go one step further:

bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue) return true;
    return false;
}

Or for the faint-hearted:

bool CanLeaveWithoutUmbrella()
{

    if(sky.Color == Color.Blue) { return true; }
    return false;
}

You could read it like that:
» CanLeaveWithoutUmbrella returns a bool. If nothing special happens, it returns false« This is the first read, from top to bottom.

And then you "parse" the condition »If the condition is met, it returns true«
You could completely skip the conditional and have understood, what this function does in the default-case. Your eye and mind only have to skim through some letters on the left side, without reading the part on the right.

I'm under the impression the else more directly states intent, by stating the fact that the code in both blocks is directly related.

Yes, that is right. But that information is redundant. You have a default case and one "exception" which is covered by the if-statement.

When dealing with complexer structures, I would choose another strategy, omitting the if or it's ugly brother switch at all.


答:
The most important goal of code is to be understandable as committed (as opposed to easily refactored, which is useful but less important). A slightly more complex Python example can be used to illustrate this:

```<code>def value(key):
    if key == FROB:
        return FOO
    elif key == NIK:
        return BAR
    [...]
    else:
        return BAZ
</code>```

This is pretty clear - it's the equivalent of a case statement or dictionary lookup, the higher-level version of return foo == bar:

```<code>KEY_VALUES = {FROB: FOO, NIK: BAR, [...]}
DEFAULT_VALUE = BAZ

def value(key):
    return KEY_VALUES.get(key, default=DEFAULT_VALUE)
</code>```

This is clearer, because even though the number of tokens is higher (32 vs 24 for the original code with two key/value pairs), the semantics of the function is now explicit: It is just a lookup.

(This has consequences for refactoring - if you wanted to have a side effect if key == NIK, you have three choices:

Revert to the if/elif/else style and insert a single line in the key == NIK case.

Save the lookup result to a value and add an if statement to value for the special case before returning.

Put an if statement in the caller.

Now we see why the lookup function is a powerful simplification: It makes the third option obviously the simplest solution, since in addition to resulting in a smaller difference than the first option it's the only one which makes sure that value does only one thing.)

Going back to OP's code, I think this can serve as a guide for the complexity of else statements: Code with an explicit else statement is objectively more complex, but more important is whether it makes the semantics of the code clear and simple. And that has to be answered on a case by case basis, since every piece of code has a different meaning.

Body:
The most important goal of code is to be understandable as committed (as opposed to easily refactored, which is useful but less important). A slightly more complex Python example can be used to illustrate this:

def value(key):
    if key == FROB:
        return FOO
    elif key == NIK:
        return BAR
    [...]
    else:
        return BAZ

This is pretty clear - it's the equivalent of a case statement or dictionary lookup, the higher-level version of return foo == bar:

KEY_VALUES = {FROB: FOO, NIK: BAR, [...]}
DEFAULT_VALUE = BAZ

def value(key):
    return KEY_VALUES.get(key, default=DEFAULT_VALUE)

This is clearer, because even though the number of tokens is higher (32 vs 24 for the original code with two key/value pairs), the semantics of the function is now explicit: It is just a lookup.

(This has consequences for refactoring - if you wanted to have a side effect if key == NIK, you have three choices:

Revert to the if/elif/else style and insert a single line in the key == NIK case.

Save the lookup result to a value and add an if statement to value for the special case before returning.

Put an if statement in the caller.

Now we see why the lookup function is a powerful simplification: It makes the third option obviously the simplest solution, since in addition to resulting in a smaller difference than the first option it's the only one which makes sure that value does only one thing.)

Going back to OP's code, I think this can serve as a guide for the complexity of else statements: Code with an explicit else statement is objectively more complex, but more important is whether it makes the semantics of the code clear and simple. And that has to be answered on a case by case basis, since every piece of code has a different meaning.


答:
Yes, there is an increase in complexity because the else clause is redundant. It's thus better to leave out to keep the code lean and mean. It's on the same chord as omitting redundant this qualifiers (Java, C++, C#) and omitting parenthesises in return statements, and so on.

A good programmer thinks "what can I add?" while a great programmer thinks "what can I remove?".


答:
I think it depends on what kind of if statement you're using.  Some if statements can be looked at as expressions, and others can only be seen as control-flow statements.

Your example looks like an expression to me.  In C-like languages, the ternary operator ?: is very much like an if statement, but it is an expression, and the else part can't be omitted.  It makes sense that an else branch can't be omitted in an expression, because the expression must always have a value.

Using the ternary operator, your example would look like this:

```<code>bool CanLeaveWithoutUmbrella()
{
    return (sky.Color == Color.Blue)
               ? true
               : false;
}
</code>```

Since it's a boolean expression, though, it really ought to be simplified all the way to

```<code>bool CanLeaveWithoutUmbrella()
{
    return (sky.Color == Color.Blue);
}
</code>```

Including an explicit else clause makes your intent clearer.  Guards can make sense in some situations, but in selecting between two possible values, neither of which is exceptional or unusual, they don't help.

Body:
I think it depends on what kind of if statement you're using.  Some if statements can be looked at as expressions, and others can only be seen as control-flow statements.

Your example looks like an expression to me.  In C-like languages, the ternary operator ?: is very much like an if statement, but it is an expression, and the else part can't be omitted.  It makes sense that an else branch can't be omitted in an expression, because the expression must always have a value.

Using the ternary operator, your example would look like this:

bool CanLeaveWithoutUmbrella()
{
    return (sky.Color == Color.Blue)
               ? true
               : false;
}

Since it's a boolean expression, though, it really ought to be simplified all the way to

bool CanLeaveWithoutUmbrella()
{
    return (sky.Color == Color.Blue);
}

Including an explicit else clause makes your intent clearer.  Guards can make sense in some situations, but in selecting between two possible values, neither of which is exceptional or unusual, they don't help.


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答:
I think the particular language you're planning to use is of very little concern when becoming a freelancer. Actual programming is probably the easiest part for most people. Yes, you'll likely need to know all of the languages/frameworks you've listed (depending on exactly what kind of work you want to find: if you don't want to do mobile development then there's little point learning Android development).

The more important skills will be learning to manage your time and your clients. You can do courses to learn that kind of stuff (I did half a term of a "small business" course, but gave up... it focused way too much on "traditional" advertising for the kind of stuff I would be doing, but that's a rant for another day). Typically, you'll learn that stuff as you go, but there are plenty of websites which give good advice (the linked to in knb's answer looks pretty good).

But if you're currently working for another company, and doing stuff that has nothing to do with what you'll be doing as a freelancer, what you should probably be doing now is:

Build a portfolio

That is, start working on projects now, whether for other people or for yourself, in your spare time. You'll want to have two or three completed projects to be able to show to prospective clients when you finally do quit your job.

What kinds of projects you work on depends on what kind of freelancing you expect to do. If you're going to do web development, build some web sites. Even if it's just a personal blog or something you need to have something to show potential clients. If you're going to be doing mobile development, build some Android or iPhone apps, etc.

Yes, it's tough to work on projects in your spare time when you've already got a full-time job. But if you're getting into freelance, you'll need to be prepared for long hours anyway (at least, when you're starting out... if you're good enough, you can earn enough to do fewer hours, but I always struggle with the "I could be working right now" niggling feeling I get when just sitting in front of the TV relaxing :p)

Title: What to learn to become freelancer?


问:
Intentionally incorrect use of language features, specifically "ref" in C#, as a hint to colleagues
I recently came across a piece of code something like this (roughly C#):

```<code>public bool ValidateStuff(ref ArrayList listOfErrors, Stuff thingsToValidate)
{
    if (!thingsToValidate.isValid() )
    {
        errors.add("New error!");
    }
}

ArrayList errors = [];
bool valid = ValidateStuff(ref errors, stuffToValidate);
</code>```

The key thing is the "ref" keyword - there is no need to use that keyword given the functionality here, and when I asked why it was there I was told that it had only been added as a kind of warning that the errors parameter is manipulated by the method, it's not purely used as input.

This immediately seemed wrong to me (ref has a purpose, and here it is not being used according to its purpose), but the idea of forcing (since you have to use ref when calling the method) a reminder of slightly counter-intuitive usage seemed reasonable, and I couldn't immediately think of a better way, apart from liberal use of comments.  What do you think?

Extra credit: how could this method be better? Perhaps by simply returning a new List of errors which is added to the main List in the calling code?  By providing two methods, one for the test and one for the errors?  Or is it fine as it is?

答:
In the early days of .NET and my endeavors into .NET land I used the same mechanism, i.e. to signal callers that the collection / container object they passed to the method was changed inside the method. But after a while I realized what is better worded in Dan Ling's answer above, namely that this is actually wrong: ref has a different meaning, and it actually illustrates something else, namely that the collection passed in can be a completely different object when the method returns.

It's better to document using XML document tags (that's what they're for!) what the behavior is of the method than signaling it through usage of 'ref'.


答:
My apologies. Been there, done that.

We've a tonne of code wired to OnClick and OnChange events. (I know this is bad). What strategies can I take with regard to converting this to the web?

Refactoring. First and foremost, and before you even start programming anything web-related. Refactor the hell out of the existing solution until you get a code base where UI and logic are separated as much as possible. This will not always be easy with legacy code, but the investment will vastly pay off as soon as you start web development.

Resist the (very tempting) idea to reference Windows controls in the logic. The goal is to keep the logic completely independent from any UI whatsoever, even if that complicates things a little. You may want to have a look at concepts like MVVM, MVP etc. to get an idea how to structure things.

The platform-specific UI should be transformed into something that holds no logic at all. However, although DRY sounds good in theory, it does not hold with distributed applications. In real life you'll find that you will have to duplicate some parts of the logic for the client's UI. Performing a server round trip for every single UI control event leads you only to a terribly slow UI, because of inavoidable request latencies. Additionally, it produces a lot of unnecessary traffic.

For security reasons, any security-related check made on the client side UI should always be performed on the server side again, before processing the request. Requests can be forged and tampered with, and not every client who speaks HTTP to your server is really a web browser.

Good luck!

Title: Converting our Windows Software to the web

Body:
We're looking at converting a software package from Windows over to the browser. It's a back office system consisting of Ledgers, Stock Control, Order Processing, etc and it's written in a legacy language (Dataflex).

The project consists of 200+ database tables, 100+ reports, 300+ Views, 100+ Dialog boxes and 200 or so Selection Lists.

I'm really struggling to get my head around the technologies that I'll need to use to convert this to a more modern web based programming language / framework. Even simple screens (Entering a stock location) seems overly complex. With the current language, I can drag a bunch of Fields to a form (a-la VB), wire in a tiny bit of database code and I've got a screen that'll allow me to find, delete, edit and change records easily. 10 minutes of development, tops.

Has anyone got any suggestions on how I can move from my current VB style programming language to one that allows similar functionality on the web?

Has anyone got any ideas how I go about working out how many man hours it's going to take to convert this sort of project to a new language on the web?

What Web Framework options are available, and how do I decide between going with something like Rails vs going with something like ASP.Net?

We've a tonne of code wired to OnClick and OnChange events. (I know this is bad). What strategies can I take with regard to converting this to the web?

I'll admit - I'm hopelessly confused by some of the newer syntaxes used by modern languages. Is there any language that allows me access to the database without having to subclass everything through IEnumerable and various weird Typecasting things.

Has anyone done anything like what we want to do? What were the pitfalls?

Sorry about the vagueness of the question. I'd be more specific but don't know where to start. Delete away if I'm asking the wrong thing or in the wrong place.


问:
Repository Pattern: Exposing Data Context to Underlying Layers
My team is in the process of updating a legacy project. We've decided to incorporate the Repository Pattern along with Entity Framework in our Data Access layer. Below is a high-level view of this organization:

IRepository<TEntity> is a generic interface used to perform common operations on an entity set:

```<code>public interface IRepository<TEntity> where TEntity : class
{
    ObjectSet<TEntity> EntitySet { get; set; }

    TEntity Get(object key);

    void Insert(TEntity entity);

    void Update(TEntity entity);

    void Save();
}
</code>```

For example if I have an Employee entity, I can create the EmployeeRepository:IRepository<Employee> object. The DataFactory class is then used as a wrapper object to take care of ObjectContext generation, disposal, and exception handling:

```<code>public class DataFactory<TContext, TEntity> : IDisposable
        where TContext : ObjectContext, new()
        where TEntity : class
{
    private bool _disposed = false;
    private TContext _context;
    private IRepository<TEntity> _repository;

    public DataFactory()
    {
        _context = new TContext();
        IRepository<TEntity> repoistory;

        bool isRepositoryFound = TryGetRepository(out repoistory);

        if (!isRepositoryFound)
        {
            throw new InvalidOperationException(
                string.Format("Unable to find repository of type {0}.", typeof(TEntity).FullName));
        }

        _repository = repoistory;
    }

    public DataFactory(TContext context, IRepository<TEntity> repository)
    {
        _context = context;
        _repository = repository;
    }

    public void Do(Action<TContext, IRepository<TEntity>> action)
    {
        try
        {
            action(_context, _repository);
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }

    public TResult DoAndReturn<TResult>(Func<TContext, IRepository<TEntity>, TResult> action)
    {
        try
        {
            return action(_context, _repository);
        }
        catch (Exception ex)
        {
            ProcessException(ex);
            return default(TResult);
        }
    }

    private bool TryGetRepository(out IRepository<TEntity> repository)
    {
        Type repositoryType = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t =>
            typeof(IRepository<TEntity>).IsAssignableFrom(t));

        if (repositoryType == null)
        {
            repository = null;
            return false;
        }

        repository = (IRepository<TEntity>)Activator.CreateInstance(repositoryType, _context );
        return true;
    }
}
</code>```

And finally to use this class in the Business Layer, we would have something like:

```<code>using (var factory = new DataFactory<MyDataContext, Employee>())
{
    factory.Do((context, repository) =>
    {
       // Interact with the repository
    });
}
</code>```

My coworker and I had a long conversation about whether the data context object should be exposed to the underlying layers in the Do() and DoAndReturn() methods. While I do see cases where having direct access to the context could be useful (for example in a case where we might want to turn on/off lazy loading for a particular entity set), I think doing so defeats the whole purpose of abstracting the Data Access layer (which is achieved by providing a common IRepository contract) since now objects can be directly accessed/manipulated through the ObjectContext.

He suggested having two different versions of these methods: one that exposes only the repository, and one that exposes both the context and repository. Is this an acceptable approach? Any suggestions are appreciated.

答:
Your setup screams one question: why did you introduce the abstractions? If you can't answer that (and I have the feeling you're not sure you can, given the nature of the question you posted) get rid of them. Entity framework and other ORMs form an abstraction of their own for database interaction, unit of work etc. Wrapping that in another set of abstraction classes which actually abstract the same thing is just creating more complexity. If I may guess, I think you created this abstraction do be able to order DB work without exposing DB oriented classes, so be able to store work through a repository without working with a context at the BL level. But in general that's just a fallacy: calling into DB oriented code through a wrapper isn't really abstracting anything.

What does help and what you didn't do, is creating classes for using the ORM with the business logic. A typical example of this is logic which makes sure different business logic methods participate in the same underlying database transaction or better: the work generated by the business logic is collected in the same unit of work.

To achieve that, it's a start to model the Business Logic actions into classes which can e.g. result in a series of commands. The BL won't have access to any DB oriented code, they just formulate what should be done. The action / command objects are then sent to class which does use DB oriented logic and which actually executes the commands / actions.

The repository pattern is 'nice' but IMHO too many times people get into trouble rather quickly as it creates a separate hierarchy of dependencies next to the entity dependencies themselves (e.g. Customer.Orders, with repositories you shouldn't be able to access that Orders collection, as they're part of the Orders repository) and isn't a real answer to what they're really struggling with.

Now it would have been great if EF had a separate unit of work class which would have been an easy solution for your problem, but alas... MS too followed Ambler's design of an ORM and ended up with a central session/context/unit-of-work hybrid.


答:
One other thing to think about in this argument is the habits each approach promotes.

if/else reframes a coding sample in the terms of branches.  As you say, sometimes this explicitness is good.  There really are two possible execution paths and we want to highlight that.

In other cases, there's only one execution path and then all those exceptional things that programmers must worry about.  As you mentioned, guard clauses are great for this.

There is, of course, the 3 or more case (n), where we usually encourage abandoning the if/else chain and using a case/switch statement or polymorphism.

The guiding principle I keep in mind here is that a method or function should have only one purpose.  Any code with an if/else or switch statement is for branching only.  So it should be absurdly short (4 lines) and only delegate to the correct method or produce the obvious result (like your example).  When your code is that short, it's hard to miss those multiple returns :)  Much like "goto considered harmful", any branching statement can be abused, so putting some critical thought into else statements is usually worth it.  As you mentioned, just having an else block provides a place for code to clump.  You and your team will have to decide how you feel about that.

What the tool is really complaining about is the fact that you have a return/break/throw inside the if block.  So as far as it's concerned, you wrote a guard clause but screwed it up.  You can choose to make the tool happy or you can "entertain" its suggestion without accepting it.


问:
What does this function do?
Does this function means its calculating x=(x-1) + x^2?</p>

```<code>Function unknown(x)
  if ( x == 1 )
    return 1
  else
    return unknown(x‐1) + x*x
</code>```

答: Well it recursively calculates x2 + (x-1)2 + (x-2)2 + ⋯ + 22 + 1.

Title: What does this function do?


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

答:
Coming late on that one but... I once worked as part of a QA team for a... let's say fairly big software project, which ultimately is part of a big telecommunications infrastructure.

Think big, as in really big, as in a few million people use it, to, well, communicate. Write, talk. Short distance and international stuff. That comes with billing as well to make sure it really matters.

The reason for me working with this team was that the technical launch date was approaching, and that they were quite late on the QA and defect identification front.

One morning I show up for our stand-up meeting, and the programme manager tells us that after a review meeting with the project's executives yesterday, they've decided that instead of having the software run on Windows 32 bits servers (which was decided like 2 years ago), they wanted it to run on HP/UX 64-bits machines.

No reason except that at the time 64 bits what becoming all the rate, so it must be better right? And totally justified. It was now only 2 weeks before the technical launch. Easy.

We fought this dearly (and with laughter).


问:
SQL Dev and Prod Environments
I have been  tasked with setting up a SQL Development environment, and i was wondering if anyone has any advice on getting this right?

So far, I have restored the prod DB onto another box, and changed all our SSIS packages to use XML configuration files so we can deploy them to either environment without changing the DB connection setting.

My plan was to restore the prod DB over the dev DB every 2 weeks (assuming its agreed by all the other developers).  Also, i was thinking i would have a UAT DB restored every 1 or 2 weeks to test deploying the changes to prod.  The UAT DB would only exist for a day or 2 to test things, and then the actual deployment would happen into the prod environment.

Can anyone thnk of anything else that would be good to do, or has any advice on other considerations etc?

答:
You want developers reaching a consensus whenever the development database is restored? Good luck with that!

I'm used to working with a similar system, but one in which the development and UAT databases are copied down from production at midnight every night. One of the great benefits of this is that your reality and the reality of production are never different for more than 24 hours (baring other changes in development). To compensate for the work lost every night, each developer has to log their scripts with a process that automatically re-runs them after the database servers have been restored from the production server.

Title: SQL Dev and Prod Environments


问:
Is DDD not appropriate for my website or should I introduce a Query Layer?
I have inherited an ASP.NET website application and the previous developer has used what I believe are some DDD concepts. I am new to DDD and I have to admit I am struggling with the practical side of it having come from an N-Tier Transaction Script background.

One of the problems with the site is that it is slow. There is no paging on huge grids and also the business logic layer pulls down way more data than is needed for 90% of operations 70% of which are reads to bind data to grids.

The general design is that the business logic layer has a Service class per aggregate root, with various "GetByX()", 'FindBestMatching()" and "Update()" type methods on it. These Service classes are the points from which trees of domain objects are created such as "Organisation" and "User."

Back in my comfortable transaction script days, my service layer was similar: there would be some logic possibly, a call into a repository (or since EF 6 direct use of EF as it can be mocked for testing) and then the call would return. The objects that were returned would be DTO type objects containing return data relevant, including possibly some POCO entity objects. These DTOs would travel to clients via webservices, be bound to ASP.NET or Silverlight grids...all was good.

My operations on my service layer could be very specific, allowing for queries like:

```<code>"GetUsersWithSurnameIncludeChildren(string surname, int skip, int take)"
</code>```

allowing for nice narrow DB queries that supported paging and eager loading of related data. It was fast and loaded only the data that was actually needed.

Now with this site I have inherited there is an actual OO model of the business domain. These classes are POCOs, not generated from EF, but EF is used database first as a repository (there is a lot of mapping between the domain objects and the EF objects). An example domain object is below (without any logic).

```<code>public class Organisation
{
    public int OrganisationID { get; set; }
    public string Name { get; set; }

    public IList<Organisation> AssociatedOrganisations { get; set; }
    public IList<User> Staff { get; set; }
    public IList<User> Managers { get; set; }

    // Business logic method implemented below here
}
</code>```

Many of the classes are essentially copies of the underlying entity framework objects, others have a significant amount of logic encapsulated within them.

The way the site works currently is that every time the OrganisationService service class creates a new Organisation domain object (and it may create a collection in one hit) it also populates ALL of the fields and collections in that object...and all of the fields and collections in those objects! A huge deep tree is created in memory and a stack of joins and unions (generated by EF) is needed to get all of the data. This is totally inappropriate for a website that mainly displays loads of flat grids.

My questions are:

1) Is an application that is 70% pulling data out of a DB for display and 30% business logic actually a bad candidate for DDD?

2) If DDD is appropriate how are scenarios like this generally designed? Should I implement a separate "Query Service" that is designed just to pull out loads of flat data for binding to pages and grids (these could just be the EF POCOS themselves) and reserve the Domain objects just for parts of the application where logic must actually be performed?

3) Should I only load data into my Domain Object reference types and collections when it is actually accessed (like EF lazy loading...)? Previous posts I have read have suggested lazy loading in a Domain Object is a code smell: DDD Lazy Loading Code Smell

I am about to buy a DDD book tonight :)

答:
If code is what you're struggling with, find the reason it's there. If there's no valid reason to be found, get rid of the code and write code that has a reason to be there. Your question is showing a list of self-inflicted problems caused by the usage of a pattern which might have solved a couple of problems but introduced a lot more, most of them technical ones.

Let me refer to my answer on SO about whether or not DDD is a waste of time: https://stackoverflow.com/questions/810606/is-ddd-a-waste-of-time/810661#810661

This might get you a bit of perspective what DDD is and what it isn't. The TL;DR is that it's not a technical solution but could (not would!) end up in a technical solution of some sort, but it doesn't have to.

The extensive graph fetching might hint at a SELECT N+1 problem through either lazy loading or loops in place which fetch code of related elements. This might be done to be able to produce a projection on the data in-memory. Looking at the class snippet though, I don't see a deep DDD influence there, as the collections otherwise wouldn't have been there.

It might be wise to see whether you actually need to fetch entity instances in a graph at all, as it might be way faster to formulate the projection of the data needed as a linq query over the entities in the model and let the DB do the set production. The resultset can then be fetched into new POCO objects, which are simply flat lists and these are then used in the UI. This is of course read/only data but for a lot of cases this is enough.


答:
I always try to write my code such that the intention is as clear as possible. Your example is lacking some context, so I'll modify it a little:

```<code>class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        if(this.color == Color.Blue)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
</code>```

Our intention seems to be that we can leave without an umbrella when the Sky is Blue. However, that simple intention is lost in a sea of code. There are several ways we can make it easier to understand.

Firstly, there's your question about the else branch. I don't mind either way, but tend to leave out the else. I understand the argument about being explicit, but my opinion is that if statements should wrap 'optional' branches, like the return true one. I wouldn't call the return false branch 'optional', since it's acting as our default. Either way, I see this as a very minor issue, and far less important than the following ones:

```<code>class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        if(this.color == Color.Blue)
        {
            return true;
        }
        return false;
    }
}
</code>```

A much more important issue is that your branches are doing too much! Branches, like everything, should be 'as simple as possible, but no more'. In this case you've used an if statement, which branches between code blocks (collections of statements) when all you really need to branch between are expressions (values). This is clear since a) your code blocks only contain single statements and b) they are the same statement (return). We can use the ternary operator ?: to narrow down the branch to only the part that's different:

```<code>class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        return (this.color == Color.Blue)
            ? true
            : false;
    }
}
</code>```

Now we reach the obvious redundancy that our result is identical to this.color == Color.Blue. I know your question asks us to ignore this, but I think it's really important to point out that this is a very first-order, procedural way of thinking: you're breaking down the input values and constructing some output values. That's fine, but if possible it's much more powerful to think in terms of relationships or transformations between the input and the output. In this case the relationship is obviously that they're the same, but I often see convoluted procedural code like this, which obscures some simple relationship. Let's go ahead and make this simplification:

```<code>class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        return (this.color == Color.Blue);
    }
}
</code>```

The next thing I'd point out is that your API contains a double-negative: it's possible for CanLeaveWithoutUmbrella to be false. This, of course, simplifies to NeedUmbrella being true, so let's do that:

```<code>class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool NeedUmbrella()
    {
        return (this.color != Color.Blue);
    }
}
</code>```

Now we can start to think about your coding style. It looks like you're using an Object Oriented language, but by using if statements to branch between code blocks, you've ended up writing procedural code.

In Object Oriented code, all code blocks are methods and all branching is done via dynamic dispatch, eg. using classes or prototypes. It's arguable whether that makes things simpler, but it should make your code more consistent with the rest of the language:

```<code>class Sky {
    bool NeedUmbrella()
    {
        return true;
    }
}

class BlueSky extends Sky {
    bool NeedUmbrella()
    {
        return false;
    }
}
</code>```

Note that using ternary operators to branch between expressions is common in functional programming.

Body:
I always try to write my code such that the intention is as clear as possible. Your example is lacking some context, so I'll modify it a little:

class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        if(this.color == Color.Blue)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Our intention seems to be that we can leave without an umbrella when the Sky is Blue. However, that simple intention is lost in a sea of code. There are several ways we can make it easier to understand.

Firstly, there's your question about the else branch. I don't mind either way, but tend to leave out the else. I understand the argument about being explicit, but my opinion is that if statements should wrap 'optional' branches, like the return true one. I wouldn't call the return false branch 'optional', since it's acting as our default. Either way, I see this as a very minor issue, and far less important than the following ones:

class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        if(this.color == Color.Blue)
        {
            return true;
        }
        return false;
    }
}

A much more important issue is that your branches are doing too much! Branches, like everything, should be 'as simple as possible, but no more'. In this case you've used an if statement, which branches between code blocks (collections of statements) when all you really need to branch between are expressions (values). This is clear since a) your code blocks only contain single statements and b) they are the same statement (return). We can use the ternary operator ?: to narrow down the branch to only the part that's different:

class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        return (this.color == Color.Blue)
            ? true
            : false;
    }
}

Now we reach the obvious redundancy that our result is identical to this.color == Color.Blue. I know your question asks us to ignore this, but I think it's really important to point out that this is a very first-order, procedural way of thinking: you're breaking down the input values and constructing some output values. That's fine, but if possible it's much more powerful to think in terms of relationships or transformations between the input and the output. In this case the relationship is obviously that they're the same, but I often see convoluted procedural code like this, which obscures some simple relationship. Let's go ahead and make this simplification:

class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool CanLeaveWithoutUmbrella()
    {
        return (this.color == Color.Blue);
    }
}

The next thing I'd point out is that your API contains a double-negative: it's possible for CanLeaveWithoutUmbrella to be false. This, of course, simplifies to NeedUmbrella being true, so let's do that:

class Sky {
    Sky(Colour c)
    {
        this.color = c;
    }
    bool NeedUmbrella()
    {
        return (this.color != Color.Blue);
    }
}

Now we can start to think about your coding style. It looks like you're using an Object Oriented language, but by using if statements to branch between code blocks, you've ended up writing procedural code.

In Object Oriented code, all code blocks are methods and all branching is done via dynamic dispatch, eg. using classes or prototypes. It's arguable whether that makes things simpler, but it should make your code more consistent with the rest of the language:

class Sky {
    bool NeedUmbrella()
    {
        return true;
    }
}

class BlueSky extends Sky {
    bool NeedUmbrella()
    {
        return false;
    }
}

Note that using ternary operators to branch between expressions is common in functional programming.


答:
They add visual cluttering in the code, so yes, they might add complexity.

However, the opposite is also true, excessive refactoring to reduce the code length can also add complexity (not in this simple case of course).

I agree with the statement that the else block states intent. But my conclusion is different, because you're adding complexity in your code in order to achieve this.

I disagree with your statement that it allows you to prevent subtle mistakes in logic.

Let's see an example, now it should only return true if the Sky is Blue and there is high Humidity, the Humidity is not high or if the Sky is Red. But then, you mistake one brace and place it in the wrong else:

```<code>bool CanLeaveWithoutUmbrella() {
    if(sky.Color == Color.Blue)
    {
        if (sky.Humidity == Humidity.High)
        {
            return true;
        }
    else if (sky.Humidity != Humidity.High)
    {
        return true;
    } else if (sky.Color == Color.Red)
    {
            return true;
    }
    } else
    {
       return false;
    }
}
</code>```

We've seen all this kind of silly mistakes in production code and can be very difficult to detect.

I would suggest the following:

I find this easier to read, because I can see at a glance that the default is false.

Also, the idea of forcing to move the contents of a block to insert a new clause, is prone to errors. This somehow relates to the open/closed principle (code should be open for extension but closed for modification). You're forcing to modify the existing code (e.g. the coder might introduce an error in braces balancing).

Finally, you're leading people to answer in a predetermined way that you think is the right one. By instance, you present a very simple example but afterwards, you state that people should not take it into consideration. However, the simplicity of the example affects the whole question:

If the case is as simple as the presented one, then my answer would be to omit any if else clauses at all.

return (sky.Color == Color.Blue);

If the case is a bit more complicated, with various clauses, I would answer:

bool CanLeaveWithoutUmbrella() {

```<code>if(sky.Color == Color.Blue && sky.Humidity == Humidity.High) {
    return true;
} else if (sky.Humidity != Humidity.High) {
    return true;
} else if (sky.Color == Color.Red) {
    return true;
}

return false;
</code>```

}

If the case is complicated and not all clauses return true (maybe they return a double), and I want to introduce some breakpoint or loggin command, I would consider something like:

```<code>double CanLeaveWithoutUmbrella() {

    double risk = 0.0;

    if(sky.Color == Color.Blue && sky.Humidity == Humidity.High) {
        risk = 1.0;
    } else if (sky.Humidity != Humidity.High) {
        risk = 0.5;
    } else if (sky.Color == Color.Red) {
        risk = 0.8;
    }

    Log("value of risk:" + risk);
    return risk;
</code>```

}

If we're not talking about a method which returns something, but instead a if-else block which sets some variable or calls a method, then yes, I would include a final else clause.

Therefore, simplicity of the example is also a factor to consider.

Body:
They add visual cluttering in the code, so yes, they might add complexity.

However, the opposite is also true, excessive refactoring to reduce the code length can also add complexity (not in this simple case of course).

I agree with the statement that the else block states intent. But my conclusion is different, because you're adding complexity in your code in order to achieve this.

I disagree with your statement that it allows you to prevent subtle mistakes in logic.

Let's see an example, now it should only return true if the Sky is Blue and there is high Humidity, the Humidity is not high or if the Sky is Red. But then, you mistake one brace and place it in the wrong else:

bool CanLeaveWithoutUmbrella() {
    if(sky.Color == Color.Blue)
    {
        if (sky.Humidity == Humidity.High)
        {
            return true;
        }
    else if (sky.Humidity != Humidity.High)
    {
        return true;
    } else if (sky.Color == Color.Red)
    {
            return true;
    }
    } else
    {
       return false;
    }
}

We've seen all this kind of silly mistakes in production code and can be very difficult to detect.

I would suggest the following:

I find this easier to read, because I can see at a glance that the default is false.

Also, the idea of forcing to move the contents of a block to insert a new clause, is prone to errors. This somehow relates to the open/closed principle (code should be open for extension but closed for modification). You're forcing to modify the existing code (e.g. the coder might introduce an error in braces balancing).

Finally, you're leading people to answer in a predetermined way that you think is the right one. By instance, you present a very simple example but afterwards, you state that people should not take it into consideration. However, the simplicity of the example affects the whole question:

If the case is as simple as the presented one, then my answer would be to omit any if else clauses at all.

return (sky.Color == Color.Blue);

If the case is a bit more complicated, with various clauses, I would answer:

bool CanLeaveWithoutUmbrella() {

if(sky.Color == Color.Blue && sky.Humidity == Humidity.High) {
    return true;
} else if (sky.Humidity != Humidity.High) {
    return true;
} else if (sky.Color == Color.Red) {
    return true;
}

return false;

}

If the case is complicated and not all clauses return true (maybe they return a double), and I want to introduce some breakpoint or loggin command, I would consider something like:

double CanLeaveWithoutUmbrella() {

    double risk = 0.0;

    if(sky.Color == Color.Blue && sky.Humidity == Humidity.High) {
        risk = 1.0;
    } else if (sky.Humidity != Humidity.High) {
        risk = 0.5;
    } else if (sky.Color == Color.Red) {
        risk = 0.8;
    }

    Log("value of risk:" + risk);
    return risk;

}

If we're not talking about a method which returns something, but instead a if-else block which sets some variable or calls a method, then yes, I would include a final else clause.

Therefore, simplicity of the example is also a factor to consider.


答:
To make a long story short, in this case, getting rid of the else keyword is a good thing.  It's totally redundant here, and depending on how you format your code, it will add one to three more completely useless lines to your code.  Consider what's in the if block:

```<code>return true;
</code>```

Therefore if the if block were to be entered into, the whole rest of the function is, by definition, not executed.  But if it is not entered into, since there are no further if statements, the whole rest of the function is executed.  It would be totally different if a return statement were not in the if block, in which case the presence or absence of an else block would have an impact, but here, it would not have an impact.

In your question, after inverting your if condition and omitting else, you stated the following:

Someone can now add a new if block based on a condition after the first example without immediately correctly recognizing the first condition is placing a constraint on their own condition.

They need to read code a little bit more closely then.  We use high-level languages and clear organization of code to mitigate these issues, but adding a completely redundant else block adds "noise" and "clutter" to the code, and we shouldn't have to invert or re-invert our if conditions either.  If they can't tell the difference, then they don't know what they're doing.  If they can tell the difference, then they can always invert the original if conditions themselves.

I forgot to mention a case in which I agree with the omission of an else block, and is when using an if block to apply a constraint that must be logically satisfied for all following code, such as a null-check (or any other guards).

That's essentially what's happening here though.  You're returning from the if block, so that if condition evaluating to false is a constraint that must be logically satisfied for all following code.

Is there an increase in complexity introduced by not including the else block?

No, it will constitute a decrease in complexity in your code, and it may even constitute a decrease in the compiled code, depending on whether certain super trivial optimizations will or will not take place.

Body:
To make a long story short, in this case, getting rid of the else keyword is a good thing.  It's totally redundant here, and depending on how you format your code, it will add one to three more completely useless lines to your code.  Consider what's in the if block:

return true;

Therefore if the if block were to be entered into, the whole rest of the function is, by definition, not executed.  But if it is not entered into, since there are no further if statements, the whole rest of the function is executed.  It would be totally different if a return statement were not in the if block, in which case the presence or absence of an else block would have an impact, but here, it would not have an impact.

In your question, after inverting your if condition and omitting else, you stated the following:

Someone can now add a new if block based on a condition after the first example without immediately correctly recognizing the first condition is placing a constraint on their own condition.

They need to read code a little bit more closely then.  We use high-level languages and clear organization of code to mitigate these issues, but adding a completely redundant else block adds "noise" and "clutter" to the code, and we shouldn't have to invert or re-invert our if conditions either.  If they can't tell the difference, then they don't know what they're doing.  If they can tell the difference, then they can always invert the original if conditions themselves.

I forgot to mention a case in which I agree with the omission of an else block, and is when using an if block to apply a constraint that must be logically satisfied for all following code, such as a null-check (or any other guards).

That's essentially what's happening here though.  You're returning from the if block, so that if condition evaluating to false is a constraint that must be logically satisfied for all following code.

Is there an increase in complexity introduced by not including the else block?

No, it will constitute a decrease in complexity in your code, and it may even constitute a decrease in the compiled code, depending on whether certain super trivial optimizations will or will not take place.


答:
You have simplified your example too much.  Either alternative may be more readable, depending on the larger situation: specifically, it depends on whether one of the two branches of the condition is abnormal.  Let me show you: in a case where either branch is equally likely, ...

```<code>void DoOneOfTwoThings(bool which)
{
    if (which)
        DoThingOne();
    else
        DoThingTwo();
}
</code>```

... is more readable than ...

```<code>void DoOneOfTwoThings(bool which)
{
    if (which) {
        DoThingOne();
        return;
    }
    DoThingTwo();
}
</code>```

... because the first one exhibits parallel structure and the second one doesn't.  But, when the bulk of the function is devoted to one task and you just need to check some preconditions first, ...

```<code>void ProcessInputOfTypeOne(String input)
{
    if (InputIsReallyTypeTwo(input)) {
        ProcessInputOfTypeTwo(input);
        return;
    }
    ProcessInputDefinitelyOfTypeOne(input);
</code>```

}

... is more readable than ...

```<code>void ProcessInputOfTypeOne(String input)
{
    if (InputIsReallyTypeTwo(input))
        ProcessInputOfTypeTwo(input);
    else
        ProcessInputDefinitelyOfTypeOne(input);
}
</code>```

... because deliberately not setting up parallel structure provides a clue to a future reader that getting input that's "really type two" here is abnormal.  (In real life, ProcessInputDefinitelyOfTypeOne would not be a separate function, so the difference would be even more stark.)

Body:
You have simplified your example too much.  Either alternative may be more readable, depending on the larger situation: specifically, it depends on whether one of the two branches of the condition is abnormal.  Let me show you: in a case where either branch is equally likely, ...

void DoOneOfTwoThings(bool which)
{
    if (which)
        DoThingOne();
    else
        DoThingTwo();
}

... is more readable than ...

void DoOneOfTwoThings(bool which)
{
    if (which) {
        DoThingOne();
        return;
    }
    DoThingTwo();
}

... because the first one exhibits parallel structure and the second one doesn't.  But, when the bulk of the function is devoted to one task and you just need to check some preconditions first, ...

void ProcessInputOfTypeOne(String input)
{
    if (InputIsReallyTypeTwo(input)) {
        ProcessInputOfTypeTwo(input);
        return;
    }
    ProcessInputDefinitelyOfTypeOne(input);

}

... is more readable than ...

void ProcessInputOfTypeOne(String input)
{
    if (InputIsReallyTypeTwo(input))
        ProcessInputOfTypeTwo(input);
    else
        ProcessInputDefinitelyOfTypeOne(input);
}

... because deliberately not setting up parallel structure provides a clue to a future reader that getting input that's "really type two" here is abnormal.  (In real life, ProcessInputDefinitelyOfTypeOne would not be a separate function, so the difference would be even more stark.)


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
Don't bother with impressing people or your bosses. Nobody is impressed by just talk.
Concentrate instead on shipping code. Ensure you are involved in projects or applications that will be used by people. More code you have in production more relevant you will be. More relevant you are to people more they will rely on you. Rest is all magic show.</p>


答:
When I see this:

```<code>if(something){
    return lamp;
}
return table;
</code>```

I see a common idiom. A common pattern, which in my head translates to:

```<code>if(something){
    return lamp;
}
else return table;
</code>```

Because this is a very common idiom in programming, the programmer who is used to seeing this kind of code has an implicit 'translation' in their head whenever they see it, that 'converts' it to the proper meaning.

I don't need the explicit else, my head 'puts it there' for me because it recognized the pattern as a whole. I understand the meaning of the entire common pattern, so I don't need small details to clarify it.

For example, read the following text:

Did you read this?

I love Paris in the springtime

If so, you are wrong. Read the text again. What's actually written is

I love Paris in the the springtime

There are two "the" words in the text. So why did you miss one of the two?

It's because your brain saw a common pattern, and immediately translated it to its known meaning. It did not need to read the entire thing detail by detail to figure out the meaning, because it already recognized the pattern upon seeing it. This is why it ignored the extra "the".

Same thing with the above idiom. Programmers who've read a lot of code are used to seeing this pattern, of if(something) {return x;} return y;. They don't need an explciit else to understand it's meaning, because their brain 'puts it there for them'. They recognize it as a pattern with a known meaning: "what's after the closing brace will run only as an implicit else of the previous if".

So in my opinion, the else is unnecessary. But just use what seems more readable.

Body:
When I see this:

if(something){
    return lamp;
}
return table;

I see a common idiom. A common pattern, which in my head translates to:

if(something){
    return lamp;
}
else return table;

Because this is a very common idiom in programming, the programmer who is used to seeing this kind of code has an implicit 'translation' in their head whenever they see it, that 'converts' it to the proper meaning.

I don't need the explicit else, my head 'puts it there' for me because it recognized the pattern as a whole. I understand the meaning of the entire common pattern, so I don't need small details to clarify it.

For example, read the following text:

Did you read this?

I love Paris in the springtime

If so, you are wrong. Read the text again. What's actually written is

I love Paris in the the springtime

There are two "the" words in the text. So why did you miss one of the two?

It's because your brain saw a common pattern, and immediately translated it to its known meaning. It did not need to read the entire thing detail by detail to figure out the meaning, because it already recognized the pattern upon seeing it. This is why it ignored the extra "the".

Same thing with the above idiom. Programmers who've read a lot of code are used to seeing this pattern, of if(something) {return x;} return y;. They don't need an explciit else to understand it's meaning, because their brain 'puts it there for them'. They recognize it as a pattern with a known meaning: "what's after the closing brace will run only as an implicit else of the previous if".

So in my opinion, the else is unnecessary. But just use what seems more readable.


答:
I think the answer is it depends.  Your code sample (as you indirectly point out) is simply returning the evaluation of a condition, and is best represented as you obviously know, as a single expression.

In order to determine whether adding an else condition clarifies or obscures the code, you need to determine what the IF/ELSE represents.  Is it a (as in your example) an expression?  If so, that expression should be extracted and used.  Is it a guard condition?  If so, then the ELSE is unnecessary and misleading, as it makes the two branches appear equivalent. Is it an example of procedural polymorphism?  Extract it.  Is it setting preconditions? Then it can be essential.

Before you decide to include or elimitate the ELSE, decide what it represents, that will tell you whether it should be present or not.


答:
This is the sum of squares of natural numbers. The sum of first n natural numbers can be represented mathematically by:

```<code>n*(n+1)*(2n+1)/6
</code>```

Title: What does this function do?

Body:
Does this function means its calculating x=(x-1) + x^2?</p>

```<code>Function unknown(x)
  if ( x == 1 )
    return 1
  else
    return unknown(x‐1) + x*x
</code>```

Body:
This is the sum of squares of natural numbers. The sum of first n natural numbers can be represented mathematically by:

n*(n+1)*(2n+1)/6


问:
How best to involve junior developer in designing an application from scratch?
We are a team of 3 developers (2 experienced devs and a junior).

We just started a brand new project. We've designed the application, concentrated efforts on choosing the right architecture and now we are laying the first lines of code. We are writing the core of it, what will be the foundation of the entire application.

This ain't no easy application either. Hard performance requirements, massively distributed, complex entity model etc.

We are all out of our comfort zone, especially the junior. He doesn't have the experience to create a good design upfront. That's not a problem though because me and the other dev are there to help and we both believe in mentoring and in building teams, but... we don't know exactly what would be the best way to do it, so that he gets an enjoyable experience and learns the maximum amount of skills.

We both realized that we didn't have a junior on new projects, only on existing ones where it was easier on the junior because he had an entire code base from which to learn and inspire. But for this app we have almost no code. We just started.

We were thinking at a few approaches:

have him try on his own for a couple of days then intervene and refactor the code together with him, steer him in the right direction then repeat => Might not be a fun experience for him since we will be pointing out his mistakes on every refactor;

have him pair programming with one of us => he might become just a "bystander" and agree with everything we do, without actually learning a lot or digesting much of the information;

have us build the skeleton of each module, with a solid design and then giving the module to him to add the missing pieces => might not be fun to pick up after us and there is the risk that he only pays attention to filling the gaps and not to the entire design.

How can we involve him in the design so that he doesn't feel left somehow outside of it and so that he learns a lot from the experience and gaining enough confidence to try it on his own?

答:
I recommend the following guidelines:

Involve the junior developer in your design meetings and solicit his input. This will get him thinking about the big picture, even if he is not ready to do the high-level design himself.

Try to isolate and clearly define a module of the application to assign to the junior developer. Describe in writing what the inputs/outputs and other requirements of the module are. Avoid assigning him a module that cannot be easily tested or which can only be tested when integrated with other yet-to-be-written modules.

Perhaps the junior developer could help in ways other than coding the core application. For example, he could write test code. Far from being menial work, writing good test scripts makes a valuable contribution to the project and also gives the junior developer a solid understanding of the project.


答:
I think it depends on which area you want that junior developer to improve. When I was (very) junior they used to give me API's that I need to build one particular confined thing, such as:

this function gives N number of personnels from Personnel table

this function provides personnel statistics given the personnel's id

->

Task: build a page with a list of personnels that shows his/her statistics when a personnel record is clicked on. Here is a simple sample page built before in the project.

The most important aspect of the given task is being solvable just by that given resources and do not require any changes in them.

Title: How best to involve junior developer in designing an application from scratch?

Body:
We are a team of 3 developers (2 experienced devs and a junior).

We just started a brand new project. We've designed the application, concentrated efforts on choosing the right architecture and now we are laying the first lines of code. We are writing the core of it, what will be the foundation of the entire application.

This ain't no easy application either. Hard performance requirements, massively distributed, complex entity model etc.

We are all out of our comfort zone, especially the junior. He doesn't have the experience to create a good design upfront. That's not a problem though because me and the other dev are there to help and we both believe in mentoring and in building teams, but... we don't know exactly what would be the best way to do it, so that he gets an enjoyable experience and learns the maximum amount of skills.

We both realized that we didn't have a junior on new projects, only on existing ones where it was easier on the junior because he had an entire code base from which to learn and inspire. But for this app we have almost no code. We just started.

We were thinking at a few approaches:

have him try on his own for a couple of days then intervene and refactor the code together with him, steer him in the right direction then repeat => Might not be a fun experience for him since we will be pointing out his mistakes on every refactor;

have him pair programming with one of us => he might become just a "bystander" and agree with everything we do, without actually learning a lot or digesting much of the information;

have us build the skeleton of each module, with a solid design and then giving the module to him to add the missing pieces => might not be fun to pick up after us and there is the risk that he only pays attention to filling the gaps and not to the entire design.

How can we involve him in the design so that he doesn't feel left somehow outside of it and so that he learns a lot from the experience and gaining enough confidence to try it on his own?


问:
Does distributing GPLd assets with a non-GPL application violate the license?
I'm trying to figure out if I can distribute the Faenza icons, which are GPL licensed, with some MIT-licensed software I'm working on. What does the GPL license really mean when applied to a non-software medium, like an icon set, that is primarily used in software applications?

If I load the icons dynamically from external files instead of compiling them into an executable, would this violate the GPL license?

If not, would it make a difference if the icons were compiled in?

If I can compile them into a program, does the license just mean I can't compile the SVG "source code" of the icons into a program?

If I can't compile the SVG source into a non-GPL program, can I load it dynamically?

Even if I'm technically allowed to package the icons with my software under some of the above conditions, would I be violating the spirit of the license?

Relevant: Does distributing non-GPLd assets with a GPL application violate the license?

答:
Here's my interpretation of it.

Definitions

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

Seems like the only reasonable interpretation is that source code refers to the SVG source and object code refers to the PNGs generated from it.

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

Under this definition, I would be conveying the the icons by packaging them with other software.

Distribution

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License...

This means I can package the PNG icons with my project, as long as I also make the SVG source available. If I'm not modifying that source, I can make it available simply by providing a link to a third-party host, If I'm reading section 6 right.

The viral part

This is the part I was worried about:

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

...

c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.

...

Looks bad so far, right? But:

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

As far as I can tell, this clause lets me off the hook with respect to the viral copyleft thing. My software project is a separate and independent work from the icon set project. This means the GPL license does not apply to my software, as long as the projects are not combined. I take this to mean that loading the icons dynamically is fine, but embedding them is not.

Summary

I'm allowed to package the GPL'd icons with my MIT-licensed software, but not embed them. If I change the SVG sources, I need to make those sources available, otherwise I need to include a link to the original sources. The GPL license from the icon project will not extend to my software project, as the distribution is an aggregate rather than an extension of the icon project.

Dual licensing

Another option, as I see it, is to dual-license my software under both the MIT and GPL licenses. Providing it under a GPL license should satisfy the requirement for any works based on a GPL'd work to also be GPL'd (considering a program to be a derivative work of an icon set seems like an extreme stretch, but apparently some people would be willing to classify it as such). As far as I can tell, while there is a requirement to release derivative works of GPL'd works under the GPL, there is no requirement stating that such works may not also be released under other licenses.