问:
Confusion in my If Else ,Else If Condition. in C#
I have three column as follows:

Month

Tech

Circle

According to this column I need to fetch the data.

In Month Column, Data is : Jan,feb, March... and so on.

In Tech Column, Data is : Gsmnqi, Gsmboi... and so on.

In Circle Column, Data is : Ap ,Kol, Mumbai.. and so on.

I want to prove four condition as follows:

if I select the month it will fetch the data related to month, tech and circle will not be selected.

if I select the month and tech it will fetch the data related to month and Tech, circle will not be selected.

if I select the month and circle it will fetch the data related to month and circle, Tech will not be selected.

if I select month, tech and circle it will fetch the data related to month, tech and circle.

But my if condition is not working, seriously I get confused in if, else and else if for this four condition.

```<code>  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "'  order by id asc");
  }
  else if (nqiSqiEntity.Month != string.Empty && nqiSqiEntity.Tech != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and TECH = '" + nqiSqiEntity.Tech + "' order by id asc");
  }
  else if (nqiSqiEntity.Month != string.Empty && nqiSqiEntity.Circle != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and CIRCLE = '" + nqiSqiEntity.Circle + "' order by id asc");
  }
  else
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and CIRCLE = '" + nqiSqiEntity.Circle + "' and TECH '" + nqiSqiEntity.Tech + "' order by id asc");
  }
</code>```

In condition, instead of string.Empty I need to put the value or I need to check if the value is present then only condition should get executed. Please kindly help me in my understanding this code.

答:
Do you see that this part is repeated every time?

```<code>"select * from K2_NQISQI with (nolock) where MONTH = '"  + nqiSqiEntity.Month
</code>```

Do you see that for the other columns you just want to AND them to the core SELECT above?

Do you see that if nqiSqiEntity.Month is string.Empty that you can't build a valid query?

Then the code would look like this:

```<code>  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "'");

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendLine("' and TECH = '" + nqiSqiEntity.Tech + "'");
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendLine("' and CIRCLE = '" + nqiSqiEntity.Circle ");
      }

      query.AppendLine( "'  order by id asc");
  }
</code>```

Below is a better way to write the appends. It avoids all the double-quote, single-quote, "+", and difficulty and error-prone string concatination.

```<code>  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendFormat("select * from K2_NQISQI with (nolock) where MONTH = '{0}'",nqiSqiEntity.Month);
      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat("' and TECH = '{0}'", nqiSqiEntity.Tech);
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat("' and CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }

      query.AppendLine( " order by id asc");
  }
</code>```

Oh, I think you want the query to be flexible for all 3 columns...

```<code>  query.AppendLine("select * from K2_NQISQI with (nolock)");

  // if at least 1 of the columns is not empty add a where clause
  if (! (nqiSqiEntity.Month != string.Empty &&
      nqiSqiEntity.Tech != string.Empty  &&
      nqiSqiEntity.Circle != string.Empty)) {

      query.AppendLine (" where ");  // we are going to add on something

      if (nqiSqiEntity.Month != string.Empty)
      {
          query.AppendFormat(" MONTH = '{0}'",nqiSqiEntity.Month);
      }

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat("' and TECH = '{0}'", nqiSqiEntity.Tech);
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat("' and CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }
  }

  query.AppendLine( " order by id asc");
</code>```

This is still messed up. So maybe the below will be less confusing, but still, lots of ifing going on!

Final Answer

```<code>  query.AppendLine("select * from K2_NQISQI with (nolock)");

  // if at least 1 of the columns is not empty add a where clause
  if (! (nqiSqiEntity.Month != string.Empty &&
      nqiSqiEntity.Tech != string.Empty  &&
      nqiSqiEntity.Circle != string.Empty)) {

      query.AppendLine (" where ");  // we are going to add on something

      if (nqiSqiEntity.Month != string.Empty)
      {
          query.AppendFormat(" MONTH = '{0}'",nqiSqiEntity.Month);

          // will there be any "and"ing ?
          if (nqiSqiEntity.Tech != string.Empty || nqiSqiEntity.Circle != string.Empty)
              query.AppendLine(" and " );
      }

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat(" TECH = '{0}'", nqiSqiEntity.Tech);

          if (nqiSqiEntity.Circle != string.Empty)
              query.AppendLine(" and " );
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat(" CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }
  }

  query.AppendLine( " order by id asc");
</code>```

Body:
Do you see that this part is repeated every time?

"select * from K2_NQISQI with (nolock) where MONTH = '"  + nqiSqiEntity.Month

Do you see that for the other columns you just want to AND them to the core SELECT above?

Do you see that if nqiSqiEntity.Month is string.Empty that you can't build a valid query?

Then the code would look like this:

  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "'");

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendLine("' and TECH = '" + nqiSqiEntity.Tech + "'");
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendLine("' and CIRCLE = '" + nqiSqiEntity.Circle ");
      }

      query.AppendLine( "'  order by id asc");
  }

Below is a better way to write the appends. It avoids all the double-quote, single-quote, "+", and difficulty and error-prone string concatination.

  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendFormat("select * from K2_NQISQI with (nolock) where MONTH = '{0}'",nqiSqiEntity.Month);
      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat("' and TECH = '{0}'", nqiSqiEntity.Tech);
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat("' and CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }

      query.AppendLine( " order by id asc");
  }

Oh, I think you want the query to be flexible for all 3 columns...

  query.AppendLine("select * from K2_NQISQI with (nolock)");

  // if at least 1 of the columns is not empty add a where clause
  if (! (nqiSqiEntity.Month != string.Empty &&
      nqiSqiEntity.Tech != string.Empty  &&
      nqiSqiEntity.Circle != string.Empty)) {

      query.AppendLine (" where ");  // we are going to add on something

      if (nqiSqiEntity.Month != string.Empty)
      {
          query.AppendFormat(" MONTH = '{0}'",nqiSqiEntity.Month);
      }

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat("' and TECH = '{0}'", nqiSqiEntity.Tech);
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat("' and CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }
  }

  query.AppendLine( " order by id asc");

This is still messed up. So maybe the below will be less confusing, but still, lots of ifing going on!

Final Answer

  query.AppendLine("select * from K2_NQISQI with (nolock)");

  // if at least 1 of the columns is not empty add a where clause
  if (! (nqiSqiEntity.Month != string.Empty &&
      nqiSqiEntity.Tech != string.Empty  &&
      nqiSqiEntity.Circle != string.Empty)) {

      query.AppendLine (" where ");  // we are going to add on something

      if (nqiSqiEntity.Month != string.Empty)
      {
          query.AppendFormat(" MONTH = '{0}'",nqiSqiEntity.Month);

          // will there be any "and"ing ?
          if (nqiSqiEntity.Tech != string.Empty || nqiSqiEntity.Circle != string.Empty)
              query.AppendLine(" and " );
      }

      if (nqiSqiEntity.Tech != string.Empty)
      {
          query.AppendFormat(" TECH = '{0}'", nqiSqiEntity.Tech);

          if (nqiSqiEntity.Circle != string.Empty)
              query.AppendLine(" and " );
      }

      if (nqiSqiEntity.Circle != string.Empty)
      {
          query.AppendFormat(" CIRCLE = '{0}'", nqiSqiEntity.Circle);
      }
  }

  query.AppendLine( " order by id asc");


问:
Isn't striving for elegance counter-productive?
Many questions have been asked about the nature of elegant code and design, but the underlying assumption seems to be that elegance is a good thing. Therefore it is acceptable or even desirable to make some extra effort to create elegant solutions.

But is it really worth it?

I am not asking what is elegant; neither am I asking about good code. I assume that "you know it when you see it", and it can also be vaguely characterized by verifying that there is nothing left to take away, in a sense that the mental model you have in your mind is expressed directly and unobscrured in the language of your choice (programming language, object oriented design, relational schema etc.), without distractions.

However, a corollary to it is that elegance is always relative (and in a way subjective); it depends on what you think the problem is and what the solution should look like. The problem of course is that both the problem domain and your understanding of it constantly change (additionally, your knowledge about the programming language / patterns / tools develops, but that's not what I am mainly concerned about).

This implies that in order to keep your design elegant, you have to constantly rethink it as the problem / your undestanding of it evolves. Practically, doing so would result in almost endless refactoring.

Furthermore, I even maintain that by striving to develop elegant solutions maintainability necessarily suffers. The most elegant solutions are the most tightly coupled to the problem domain, for if they weren't, then there would be something to take away from it, hence they would not be most elegant anymore. If there is something abundant in your solution, then you can simplify it and make it more elegant by removing that abundant part, right?

But then, sometimes, when you have a really elegant design and are required to implement a change, you first have to "untighten" your solution, just in order to be able to make an unforeseen (as are most of them) change at all. However, the open/closed-principle states that this should not be necessary. So, another more concrete formulation of the question is:

To some degree, aren't elegance and open/closed-principle at odds with each other?

What do you think?

答:
I see no justice in this statement:

... by striving to develop elegant solutions maintainability
  necessarily suffers. The most elegant solutions are the most tightly
  coupled to the problem domain, for if they weren't, then there would
  be something to take away from it, hence they would not be most
  elegant anymore.

An example of an elegant solution that is not tightly coupled to the domain is generic sort algorithms. You have six items in a list (vector/array/whatever) that need to be sorted; do you hand craft the 12 lines of code that take advantage of the inherent partial ordering of the list, or do you invoke a sort function in one line?

Similarly, do you explicitly craft an algorithm and re-implement it several places or do you extract a method and make it generic?

In both of those cases, the elegant solution is much shorter and more understandable. The given solutions are also more maintainable.

This is a straw man argument:

in order to keep your design elegant, you have to constantly rethink
  it as the problem / your undestanding of it evolves. Practically,
  doing so would result in almost endless refactoring.

Striving for elegance is always balanced against all of the other needs of the project.

ContentLicense: CC BY-SA 3.0


答:
If you write a statement

```<code>if(A)
{
    // ... foo
}
else if(A && B)
{
    // ... bar
}
</code>```

the second block will never be executed. Since if A is true, it does not matter what B is, the first block gets executed. if A is false, none of the two conditions is true, so none of the two blocks are executed. What you can do here is switch orders:

```<code>if(A && B)
{
    // ... bar
}
else if(A)
{
    // ... foo
}
</code>```

(the idea is to test the most restrictive condition first, and only if it fails, test the less restrictive condition).

However, in your case the whole logic is unnecessary complicated, and your code contains  too many duplicates. The four times repetition of

```<code>  query.AppendLine("select * from K2_NQISQI with (nolock) where ...")
</code>```

is a blatant code smell. I suggest to solve this along the lines of:

```<code> var conditions = new List<string>();
 if (nqiSqiEntity.Month != string.Empty)
     conditions.Add("MONTH = '" + nqiSqiEntity.Month+"'");
 if(nqiSqiEntity.Tech != string.Empty)
     conditions.Add("TECH = '" + nqiSqiEntity.Tech+"'");
 if(nqiSqiEntity.Circle != string.Empty)
     conditions.Add("CIRCLE = '" + nqiSqiEntity.Circle + "'");
 if(conditions.Count>0)
 {
      string finalCondition= "select * from K2_NQISQI with (nolock) WHERE " +
                            string.Join(" and ", conditions.ToArray())
                            + " order by id asc";
      query.AppendLine(finalCondition);
 }
</code>```

beware, this is "air code", and it does not deal with the fact that in your question nqiSqiEntity.Month is always required for creating the condition.

Title: Confusion in my If Else ,Else If Condition. in C#

Body:
I have three column as follows:

Month

Tech

Circle

According to this column I need to fetch the data.

In Month Column, Data is : Jan,feb, March... and so on.

In Tech Column, Data is : Gsmnqi, Gsmboi... and so on.

In Circle Column, Data is : Ap ,Kol, Mumbai.. and so on.

I want to prove four condition as follows:

if I select the month it will fetch the data related to month, tech and circle will not be selected.

if I select the month and tech it will fetch the data related to month and Tech, circle will not be selected.

if I select the month and circle it will fetch the data related to month and circle, Tech will not be selected.

if I select month, tech and circle it will fetch the data related to month, tech and circle.

But my if condition is not working, seriously I get confused in if, else and else if for this four condition.

```<code>  if (nqiSqiEntity.Month != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "'  order by id asc");
  }
  else if (nqiSqiEntity.Month != string.Empty && nqiSqiEntity.Tech != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and TECH = '" + nqiSqiEntity.Tech + "' order by id asc");
  }
  else if (nqiSqiEntity.Month != string.Empty && nqiSqiEntity.Circle != string.Empty)
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and CIRCLE = '" + nqiSqiEntity.Circle + "' order by id asc");
  }
  else
  {
      query.AppendLine("select * from K2_NQISQI with (nolock) where MONTH = '" + nqiSqiEntity.Month + "' and CIRCLE = '" + nqiSqiEntity.Circle + "' and TECH '" + nqiSqiEntity.Tech + "' order by id asc");
  }
</code>```

In condition, instead of string.Empty I need to put the value or I need to check if the value is present then only condition should get executed. Please kindly help me in my understanding this code.

Body:
If you write a statement

if(A)
{
    // ... foo
}
else if(A && B)
{
    // ... bar
}

the second block will never be executed. Since if A is true, it does not matter what B is, the first block gets executed. if A is false, none of the two conditions is true, so none of the two blocks are executed. What you can do here is switch orders:

if(A && B)
{
    // ... bar
}
else if(A)
{
    // ... foo
}

(the idea is to test the most restrictive condition first, and only if it fails, test the less restrictive condition).

However, in your case the whole logic is unnecessary complicated, and your code contains  too many duplicates. The four times repetition of

  query.AppendLine("select * from K2_NQISQI with (nolock) where ...")

is a blatant code smell. I suggest to solve this along the lines of:

 var conditions = new List<string>();
 if (nqiSqiEntity.Month != string.Empty)
     conditions.Add("MONTH = '" + nqiSqiEntity.Month+"'");
 if(nqiSqiEntity.Tech != string.Empty)
     conditions.Add("TECH = '" + nqiSqiEntity.Tech+"'");
 if(nqiSqiEntity.Circle != string.Empty)
     conditions.Add("CIRCLE = '" + nqiSqiEntity.Circle + "'");
 if(conditions.Count>0)
 {
      string finalCondition= "select * from K2_NQISQI with (nolock) WHERE " +
                            string.Join(" and ", conditions.ToArray())
                            + " order by id asc";
      query.AppendLine(finalCondition);
 }

beware, this is "air code", and it does not deal with the fact that in your question nqiSqiEntity.Month is always required for creating the condition.


问:
How to handle hidden folders on deployed website
Our security team at work did a security scan of our soon-to-be-deployed website and one of the items that was found was "Hidden Directory Detected". It shows up for 3 different folders, aspnet_client, scripts, and content.

The software recommends to throw a 404 instead of a 403, or to remove the folders completely. First, are the folders actually needed? How can I determine which folders in my visual studio project are actually needed in order for the site to actually run (without removing folders one-at-a-time and trying to access the site)?

What is the proper way to handle this/resolve the security scan alert? Do I need to add special routing rules in the routeconfig.cs for when these paths are accessed?

Edit, I should note that this is WebApi/REST service, not a regular MVC site. (Therefore, using the CustomErrors configuration section will not work)

答:
After much googling, here's the solution that I have implemented. I'm not sure if it's the best practice for this sort of thing, but it's working in my scenario.

Scroll down to the answer about implementing the NoAccessHandler : IHttpHandler

http://forums.asp.net/t/1478217.aspx?Make+IIS+return+a+404+status+code+instead+of+403

Config section needed:

```<code><httpHandlers>
      <add verb="*" path="docs/*" validate="false" type="MyNameSpace.NoAccessHandler"/>
</httpHandlers>

<system.webServer>
        <handlers>
      <add name="NoAccess" verb="*" path="docs/*"  preCondition="integratedMode" type="MyNameSpace.NoAccessHandler"/>
    </handlers>
</system.webServer>
</code>```

And the Handler code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyNameSpace
{
    public class NoAccessHandler: IHttpHandler
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.StatusCode = 404;
        }

        #endregion
    }
}
</code>```

Body:
After much googling, here's the solution that I have implemented. I'm not sure if it's the best practice for this sort of thing, but it's working in my scenario.

Scroll down to the answer about implementing the NoAccessHandler : IHttpHandler

http://forums.asp.net/t/1478217.aspx?Make+IIS+return+a+404+status+code+instead+of+403

Config section needed:

<httpHandlers>
      <add verb="*" path="docs/*" validate="false" type="MyNameSpace.NoAccessHandler"/>
</httpHandlers>

<system.webServer>
        <handlers>
      <add name="NoAccess" verb="*" path="docs/*"  preCondition="integratedMode" type="MyNameSpace.NoAccessHandler"/>
    </handlers>
</system.webServer>

And the Handler code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyNameSpace
{
    public class NoAccessHandler: IHttpHandler
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.StatusCode = 404;
        }

        #endregion
    }
}


问:
Why are floats called "real numbers" in some languages?
Some programing languages, notably Pascal, have a type of numbers called "real".

However, mathematically speaking, these types aren't real. For them to be "real", these types have to be able to represent any real number. Real numbers like 1/3 and irrationals, however, can't be represented in floating point. So why do some programing languages call these types "real"?

答: Short answer: because it is the default approximation of a real number the language in question provides.</p>


答:
it can also be vaguely characterized by verifying that there is nothing left to take away, in a sense that the mental model you have in your mind is expressed directly and unobscrured in the language of your choice (programming language, object oriented design, relational schema etc.), without distractions.

I'm not sure I agree with this. I know of many barebones, or concise solutions for a problem that are directly and clearly implemented without being elegant. I mean, if I brute force your password, the code will be a clear description of what I'm trying to accomplish - but the solution itself isn't elegant in the least.

To me, an elegant solution is one where things "fall away". Consider the composite pattern. Many times, judicious use of this pattern yields this sort of effect. Without the pattern, the "is this a single thing, or is it many things" problem has to be propagated everywhere that uses the interface. By using the composite pattern, you hide away that complexity so that consumers need not care.

Elegant solutions are ones that don't just solve a problem, but prevent problems from ever happening. So no, striving for elegance isn't counter productive.

Title: Isn't striving for elegance counter-productive?

Body:
Many questions have been asked about the nature of elegant code and design, but the underlying assumption seems to be that elegance is a good thing. Therefore it is acceptable or even desirable to make some extra effort to create elegant solutions.

But is it really worth it?

I am not asking what is elegant; neither am I asking about good code. I assume that "you know it when you see it", and it can also be vaguely characterized by verifying that there is nothing left to take away, in a sense that the mental model you have in your mind is expressed directly and unobscrured in the language of your choice (programming language, object oriented design, relational schema etc.), without distractions.

However, a corollary to it is that elegance is always relative (and in a way subjective); it depends on what you think the problem is and what the solution should look like. The problem of course is that both the problem domain and your understanding of it constantly change (additionally, your knowledge about the programming language / patterns / tools develops, but that's not what I am mainly concerned about).

This implies that in order to keep your design elegant, you have to constantly rethink it as the problem / your undestanding of it evolves. Practically, doing so would result in almost endless refactoring.

Furthermore, I even maintain that by striving to develop elegant solutions maintainability necessarily suffers. The most elegant solutions are the most tightly coupled to the problem domain, for if they weren't, then there would be something to take away from it, hence they would not be most elegant anymore. If there is something abundant in your solution, then you can simplify it and make it more elegant by removing that abundant part, right?

But then, sometimes, when you have a really elegant design and are required to implement a change, you first have to "untighten" your solution, just in order to be able to make an unforeseen (as are most of them) change at all. However, the open/closed-principle states that this should not be necessary. So, another more concrete formulation of the question is:

To some degree, aren't elegance and open/closed-principle at odds with each other?

What do you think?


答:
Isn't striving for elegance counter-productive?

Past a certain point, yes.

But is it really worth it?
  I am not asking what is elegant; neither am I asking about good code. I assume that "you know it when you see it"

Well ... you probably should [ask "what is elegant"]. "You know it when you see it" implies that you don't know it, until you see it as well -- and then, your effort to write elegant code is effort spent with lacking direction (or, effort spent in the wrong direction).

This implies that in order to keep your design elegant, you have to constantly rethink it as the problem / your undestanding of it evolves. Practically, doing so would result in almost endless refactoring.

No, it doesn't imply that you should constantly rething the problem. You should think the problem well at the beginning. The more thought you put in at the beginning, the less you will have to change afterwards. If you do not have a clear thought of where you are/should be (at the beginning) then you will need to change the code. To avoid endless refactoring, you should (first) decide how the solution should look like, how an elegant solution should look like, then implement that.

You will know you are doing it right, when you end up spending up to 10 times* on interface design (and tests) then you spend on implementation.

Furthermore, I even maintain that by striving to develop elegant solutions maintainability necessarily suffers.

If a solution is not maintainable, how can you call it elegant? An elegant solution should be (by my definition) a solution that fits the problem, design, maintainability and performance requirements well. Otherwise, it may not be a solution to your problem at all (let alone an elegant one). This also makes my point above (about needing to ask "what is elegant" before you go searching for elegant solutions).

The most elegant solutions are the most tightly coupled to the problem domain, for if they weren't, then there would be something to take away from it, hence they would not be most elegant anymore.

In my book, those are not elegant solutions, they are inflexible solutions (and by definition, as opposed to elegant as you can get).

If there is something abundant in your solution, then you can simplify it and make it more elegant by removing that abundant part, right?

Uhh ... no. Doing so would depend on what you would gain by such a change, and if the gain is worth it at all.

you first have to "untighten" your solution

AFAIK, this is called implementing a loosely coupled design, and is considered a cornerstone of writing elegant code. It is not something that goes against elegant design, it is a part of it.

To some degree, aren't elegance and open/closed-principle at odds with each other?

No. An elegant solution would be one that took the open/closed principle into account from the start.

this idea was taken from Alexander Stepanov, the designer of the C++ STL (and it's an idea I can confirm through experience).


问:
Does CC0 allow sublicensing of derived works?
I want to release all my future FOSS projects under a "public domain" license such as CC0. This is in order to avoid the requirement for attribution present in most FOSS licenses, mainly when the code is compiled into a binary, but also when somebody decides to copy a small portion of my code into their own open source project.

So suppose somebody copies a method from my code into their own, which they are planning to release under an MIT license. In order to release the code under MIT, they must claim copyright of the code; but can they claim copyright of the whole if a portion of the code was not their creation? Is that what it means to claim copyright of a derived work?

It may seem strange that somebody could take a piece of public domain code, modify it, and apply a new license to the modified version that imposes further restrictions on its usage, such as the attribution requirement of MIT. But since their additional restrictions would apply only to the modified version and not the original version, this seems legitimate.

My main concern is maximizing the ways in which people can utilize my code, without worrying about licensing requirements, and also to avoid a viral effect where any derivative works have to be themselves licensed under CC0.

答:
#include <ianal.h>

Document style licenses are often a poor fit for source code.  Of these, the ones that are a gift (and that is a word with legal implications) are the most problematic.

Public domain, as seen in the US, is a gift.  In particular, a gift may be revoked for any reason.  This makes something that is in the public domain possibly treacherous for open source - when the gift is revoked, it suddenly has back its full copyright protections.

There are also countries that don't recognize public domain at all.  According to a creative commons survey countries such as Belgium, Denmark, France, Germany (and the list goes on and on) don't recognize public domain at all, or only recognize it after the copyright has expired.  Of the countries that do recognize public domain, many allow the revocation of it if the copyright hasn't expired.

There are anecdotes (I can't find it at the moment) of an open source project that was completely released under public domain that wasn't useable at all in those countries - and so for people there to use and modify the source, they had to get a commercial license (which cost $$$).

So, on to CC0.  The key to CC0 is that it has some wording in there to make it a license rather than a gift.

To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver").

Note the 'permanently' and 'irrevocably' words being used.  CC0 cannot be revoked.  It also goes on to state that the heirs cannot revoke it either (an issue with public domain).

Background reading: http://www.rosenlaw.com/lj16.htm

As to the core question of if CC0 can be sublicensed?  GNU.org lists licenses that are compatible with the GPL on Various Licenses and Comments about Them lists the GPL as a compatible license.  They also list public domain as being compatible tough note the issues that I raised in the first part... I'm sure that GNU has good lawyers who will fight if something is revoked or there are issues in those countries (on the other hand, I don't and would be vary wary of accepting public domain donations to an open source project).

All that said, CC0 still strikes me as awkward in that the license is different for different countries recognizing different parts being contrary to local law (I know that Creative Commons has done a great job to the best of their ability in crafting this).  There are places where parts of the permissive license for CC0 would have difficulty (France - Right to withdrawal or reconsider I am still not a lawyer, much less one versed in French law written in English).

The thing is, programmers who are going to be caring at all about the license already know how to deal with the MIT, or BSD, or GPL.  Other licenses require some legal reading for the project as to if you can include them or not.

I'd also point to http://choosealicense.com/licenses/ - scrolling down to the bottom for the "public domain" one, note that the unlicense allows for sub licensing while CC0 does not.

So suppose somebody copies a method from my code into their own, which they are planning to release under an MIT license. In order to release the code under MIT, they must claim copyright of the code; but can they claim copyright of the whole if a portion of the code was not their creation? Is that what it means to claim copyright of a derived work?

Give http://www.rosenlaw.com/lj19.htm a read for background (note that this reading of derative works is in conflict with the GPL's understanding - but since we're not talking about the GPL the reading of it is much more common sense).

There are several ways to address the approach.  You could put the function in another library and point out that library is a derivative work, licensed under however it was obtained (which is compatible with the rest of the project). The copyright of the rest of the project is not a derivative work (GPL questions of static and dynamic linking aside - they try to make the derivative work extend to as many things as possible).

For example, if code snippet foo was from an BSD licensed work, you could stick foo in its own library.  That would be a derivative work of an apache product and licensed under BSD license.  Then the rest of your code would be MIT licensed (for example) and not a derivative work.  And since the BSD and MIT licenses are compatible, thats the end of the story.

I just used BSD as an example for your license, but really it could be anything as long as it was compatible with the license I'm using.  And while CC0 is compatible with everything - there are other, better understood licenses for software that are similarly nearly universally compatible.  The BSD 2 clause or MIT, or Apache 2.0 licenses are ones people understand.

To get the widest use of your code, you should use a license that people know and understand.  If you chose something that is less well understood programmers may be less likely to use it because of the possible legal implications that they'd have to ask a lawyer about.  If you have to check if CC0 is sub licensable or not, you don't use it.  If you see a BSD license, you know what you can do with it.

You could always go with WTFPL.

I am still not a lawyer.


答:
When you take time to study elegance outside the constructs of code, you gain an appreciation for what truly is elegant.  According to the great art masters (like Da Vinci), and some of the greatest mathematical minds (like Einstein), a very common attribute of elegance is simplicity.

What Elegance Is Not

In reading your question, it seems to me that you are equating elegance with fancy solutions that use complex black boxes that hide implementation details from you.  That is the furthest thing from elegance, for the following reasons:

Hidden details and swallowed exceptions can hide what the real problem is.

Reflection as a major feature of a framework/etc. makes it very difficult to trace what is going on in an application.

It muddies understanding of the code, and of the problem domain.

It requires you to learn a new language and thought process in addition to the language you are using.

These are attributes of the cumbersome problems that probably started as a good idea, and then carried too far.  These issues all complicate maintaining code, have difficult to grasp concepts, and in general do not improve the bottom line.  Even if some people have a simple solution and tout solutions like this as "elegant", if it doesn't remain elegant in a more complex solution then it truly is not elegant.

Defining Elegance

Elegant code simplifies the solution in a way that is comprehensible by all members of the team.  If you are working with an object oriented language, an elegant solution does not force you to change the way you think in terms of a functional language.  The reverse also applies.  The following are attributes of elegant solutions:

Debugging and following code flow is very easy

It greatly reduces clutter code that hides the intent of a method

The concepts and method of thinking fit well within the language used, and truly elegant also makes the problem domain easier to comprehend in the code.

It improves the efficiency of the developers working with the code

Can we learn newer ways of approaching a problem that are more elegant than the ones we are using?  Absolutely.  Is it worth retrofitting existing code with the newer, simpler, and more elegant solution?  Not always.  That's a project management decision that requires you to balance the cost of the change against what gain that solution will provide.

Should We Pursue Elegance?

The pursuit of elegance is synonymous with simplifying code and making it more understandable.  Anything you can do to lighten the already heavy cognitive load a developer has when maintaining code, the better.  Sometimes all you can afford to do are small improvements (light refactoring) here and there as you go in and work on code.  Sometimes there is so much code rot due to changing requirements that you really need to rewrite a section of the code to satisfy the current needs better and enable new features.  It doesn't change the fact that pursuing elegance is synonymous with making your life easier and improving the maintainability of the code.


问:
Should we avoid using design patterns in constantly changing projects?
A friend of mine is working for a small company on a project every developer would hate: he's pressured to release as quickly as possible, he's the only one who seem to care about technical debt, the customer has no technical background, etc.

He told me a story which made me think about the appropriateness of design patterns in projects like this one. Here's the story.

We had to display products at different places on the website. For example, content managers could view the products, but also the end users or the partners through the API.

Sometimes, information was missing from the products: for example, a bunch of them didn't have any price when the product was just created, but the price wasn't specified yet. Some didn't have a description (the description being a complex object with modification histories, localized content, etc.). Some were lacking shipment information.

Inspired by my recent readings about design patterns, I thought this was an excellent opportunity to use the magical Null Object pattern. So I did it, and everything was smooth and clean. One just had to call product.Price.ToString("c") to display the price, or product.Description.Current to show the description; no conditional stuff required. Until, one day, the stakeholder asked to display it differently in the API, by having a null in JSON. And also differently for content managers by showing "Price unspecified [Change]". And I had to murder my beloved Null Object pattern, because there was no need for it any longer.

In the same way, I had to remove a few abstract factories and a few builders, I ended up replacing my beautiful Facade pattern by direct and ugly calls, because the underlying interfaces changed twice per day for three months, and even the Singleton left me when the requirements told that the concerned object had to be different depending on the context.

More than three weeks of work consisted of adding design patterns, then tearing them apart one month later, and my code finally became spaghetti enough to be impossible to maintain by anyone, including myself. Wouldn't it be better to never use those patterns in the first place?

Indeed, I had to work myself on those types of projects where the requirements are changing constantly, and are dictated by persons who don't really have in mind the cohesion or the coherence of the product. In this context, it doesn't matter how agile you are, you'll come with an elegant solution to a problem, and when you finally implement it, you learn that the requirements changed so drastically, that your elegant solution doesn't fit any longer.

What would be the solution in this case?

Not using any design patterns, stop thinking, and write code directly?

It would be interesting to do an experience where a team is writing code directly, while another one is thinking twice before typing, taking the risk of having to throw away the original design a few days later: who knows, maybe both teams would have the same technical debt. In the absence of such data, I would only assert that it doesn't feel right to type code without prior thinking when working on a 20 man-month project.

Keep the design pattern which doesn't make sense any longer, and try to add more patterns for the newly created situation?

This doesn't seem right neither. Patterns are used to simplify the understanding of the code; put too much patterns, and the code will become a mess.

Start thinking of a new design which encompasses the new requirements, then slowly refactor the old design into the new one?

As a theoretician and the one who favors Agile, I'm totally into it. In practice, when you know that you'll have to get back to the whiteboard every week and redo the large part of the previous design and that the customer just doesn't have enough funds to pay you for that, nor enough time to wait, this probably won't work.

So, any suggestions?

答:
A design pattern's complexity can bite you if the problem it was supposed to solve suddenly disappears. Sadly, due to enthusiasm and popularity of design patterns, this risk is rarely made explicit. Your friend's anecdote helps a lot to show how patterns don't pay off. Jeff Atwood has some choice words about the topic.

Document variation points (they are risks) in requirements

Many of the more complex design patterns (Null Object not so much) contain the concept of Protected variations, that is "Identify points of predicted variation or instability; assign responsibilities to create a stable interface around them." Adapter, Visitor, Facade, Layers, Observer, Strategy, Decorator, etc. all exploit this principle. They "pay off" when the software needs to be extended in the dimension of the expected variability, and the "stable" assumptions remain stable.

If your requirements are so unstable that your "predicted variations" are always wrong, then the patterns you apply will cause you pain or be unneeded complexity at best.

Craig Larman speaks of two opportunities to apply Protected variations:

variation points - in the existing, current system or requirements, such as multiple interfaces that must be supported, and

evolution points - speculative points of variation which are not present in existing requirements.

Both are supposed to be documented by developers, but you should probably have customer commitment to the variation points.

To manage risk, you could say that any design pattern applying PV should be traced to a variation point in the requirements signed off by the customer. If a customer changes a variation point in the requirements, your design may have to change radically (because you likely invested in design [patterns] to support that variation). No need to explain cohesion, coupling, etc.

For example, your customer wants the software to work with three different legacy inventory systems. That's a variation point you design around. If the customer drops that requirement, then of course you have a bunch of useless design infrastructure. The customer needs to know that variation points cost something.

CONSTANTS in source code are a simple form of PV

Another analogy to your question would be to ask if using CONSTANTS in source code is a good idea. Referring to this example, let's say the customer dropped the need for passwords. Thus the MAX_PASSWORD_SIZE as a constant spread throughout your code would become useless and even a hindrance to maintenance and legibility. Would you blame the use of CONSTANTS as the reason?


问:
Desktop client server application, limiting text area field compromise with customers
We have a textarea field in a desktop client server application which in the end stores all the data in a database server, this text area is used to take notes and similar text areas have been put throughout our application as a marketing choice so that users can never blame the application for missing some fields and the marketing department can always answer "put it in the notes field".

Recently however we realised some customers use the notes area heavily to write letters or copy paste documents, so we had to increase the notes field in the database from 1024 to 10240, we are realising however that this way the desktop application takes always more time to download all this backlog of information.

What is the compromise between giving practically no limit to user input length and letting the users use it as they deem necessary and putting a strict limit justifying the choice as "performance mandated"?

答:
similar text areas have been put throughout our application as a marketing choice so that users can never blame the application for missing some fields and the marketing department can always answer "put it in the notes field"

Sloppy design leads to sloppy product (a "write-it-all-here" field actually used to "write-it-all-there", what a surprise).

The compromise depends of the usage, there is no general rule ("560KB should be enough for everyone"). A few hints:

Take your current data and find percentiles per size. Probably, a high percentaje of your records won't need so much data

Identify how people are using the field

maybe some uses require its own data field, which could allow also for standardization

follow-up notes should be in separate items, not in the same field used by the user. Most probably, an 1-N relationship with the original record.

to write letters or copy paste documents, any reason not to allow file uploads?

Once you have dealt with these needs of your users and have provided them a better way to get them covered, you can reduce back the size of the text area.


问:
Should I still consider using Appcelerator Titanium for building mobile apps if I don't have any web dev skills?
I'm an experienced desktop developer who's recently begun writing iOS apps and would like to venture into Android development as well.  I've been hearing a lot of talk surrounding the Appcelerator Titanium framework lately, but I'm not sure I fully understand it's purpose.  As I understand it, it's a framework for building native mobile apps using web technologies.  If I don't have any web dev skills, are there any ways that using Appcelerator Titanium would benefit me?

Thanks for your thoughts, I'm going to continue researching this right now.

答:
From their intro (my emphasis):

Titanium lets you create native mobile, tablet and desktop application experiences using existing web skills like Javascript, HTML, CSS, Python, Ruby, and PHP

You say:

I don't have any web dev skills

So for you:

Pros:

Cross Platform

Cons:

Cross Platform

In other words, if cross platform is a big deal to you and you don't otherwise have the skills, time, people, etc. to develop a cross-platform app using native languages, then it might be worth looking into.

If you are prepared to deal with dependence on a platform that will always lag behind native development for new features, another layer to introduce bugs (union of bugs), fewer features (intersection of features) a poorer user experience, a smaller development community, and some amount of risk that the SDK could die off completely.

ContentLicense: CC BY-SA 2.5


问:
Why does C have no competitors in low level stuff?
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?

答:
To supplement other answers, don't forget that C was written by Bell Labs, largely for the Unix project. Unix itself was rewritten in C the year the language was released. The Unix system tools and libraries were C-based and followed C conventions. In short, C is the official Unix systems language, and today we're all using Unix derivatives (with the exception of the Windows people).

On top of that, anything more high-level than C begins to sacrifice efficiency and programmer freedom for the often commendable goal of safety. For example, try allocating a dynamically-sized block of heap memory in Go. While Go is considered a systems language, it's difficult to do such low-level manipulations in it; you often can't without significant trickery or overhead. Good C programmers are confident in their ability to use the language properly, and don't want to relinquish such complete power and fine-grained control.


答:
There are languages competing with C (for low level or system programming): Rust, Cyclone, ... and perhaps Go (which is probably slightly higher level).

And there are more academic languages competing with C.

Title: Why does C have no competitors in low level stuff?

Body:
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?


问:
How to hide AOP implementation dependency without breaking encapsulation?
I have the concept of a SlowLoading thing:

```<code>public interface SlowLoading {
  boolean hasLoaded();
}
</code>```

I also have a component MyComponent:

```<code>public interface myComponent{
  void doSomething();
}
</code>```

My implementation covers both:

```<code>public class MyComponentImpl implements SlowLoading, MyComponent {
   // omitted for brevity
}
</code>```

I have a container (interface omitted for brevity) which returns MyComponent:

```<code>public class MyContainerImpl implements MyContainer{
  @Inject private MyComponent component;

  @Override
  public MyComponent doSomething(){
    // magic happens
    return myComponent;
  }
}
</code>```

I also have an AOP component that intercepts the return of slow loading things and implicitly waits for them to load before returning:

```<code>@Pointcut("execution(SlowLoading+ *(..) )")
  public void returnsSlowLoadingThing() {
}
</code>```

However, at present the MyContainer method is not proxied, since the return value does not implement SlowLoading.

What is the best way to encapsulate this behaviour?

Options I've considered:

Make MyComponent extend SlowLoading.  This feels like a code smell and breaking of encapsulation - bleeding implementation into the interface.  A client does not care if it is slow loading or not.

Inject MyComponentImpl directly into my container and return it explicitly (co-variant returns).  Again, this feels like it is breaking encapsulation and the point of programming to interfaces, but feels better than the above, since it is done at a lower level and hidden behind the interface (implementation detail).  However it is breaking the encapsulation of the AOP functionality which should be orthogonal and transparent.

Perform the AOP wait before invoking a method on a SlowLoading thing.  This seems the most appropriate, but I've not been able to get this working so far.

答:
How about intercepting every Method of Container subclasses that return Objects?

The advantage of this approach is that your core interfaces don't need to now anything about the "SlowLoading" concept. One disadvantage on the other hand is that you may intercept more calls than necessary - which may or may not a problem for your use-case.

```<code>import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TransparentLoading {

    @Pointcut("execution(public Object+ Container.*(..))")
    public void executionOfObjectReturningContainerMethod(){}

    @Around("executionOfObjectReturningContainerMethod()")
    public Object performLazyLoadingIfNecessary(ProceedingJoinPoint joinPoint) throws Throwable{

        Object result = joinPoint.proceed();

        if(result instanceof SlowLoading){
            result = ensureLoaded((SlowLoading)result);
        }

        return result;
    }

    public static Object ensureLoaded(SlowLoading result) {

        if(!result.isLoaded()){
            result.load();
        }

        return result;
    }
}
</code>```

OwnerDisplayName: Tim

Body:
How about intercepting every Method of Container subclasses that return Objects?

The advantage of this approach is that your core interfaces don't need to now anything about the "SlowLoading" concept. One disadvantage on the other hand is that you may intercept more calls than necessary - which may or may not a problem for your use-case.

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TransparentLoading {

    @Pointcut("execution(public Object+ Container.*(..))")
    public void executionOfObjectReturningContainerMethod(){}

    @Around("executionOfObjectReturningContainerMethod()")
    public Object performLazyLoadingIfNecessary(ProceedingJoinPoint joinPoint) throws Throwable{

        Object result = joinPoint.proceed();

        if(result instanceof SlowLoading){
            result = ensureLoaded((SlowLoading)result);
        }

        return result;
    }

    public static Object ensureLoaded(SlowLoading result) {

        if(!result.isLoaded()){
            result.load();
        }

        return result;
    }
}


问:
How to prove that following practices and industrial standards are profitable, and investment in refactoring are good
I started working in a company not much time ago, and what I see a lot inside a project is a high amount of low quality code and some custom ideas instead of industry standards and selected best practices.

But when I trying to talk with manager about that, I often see the answers, that guys who doing that make things quick and they are good etc, etc, etc

答:
This is fundamentally a cultural issue. First of all, be careful of thinking you can "prove" that a different methodology is better. With time and experience, you'll get better about "persuading" your colleagues about better practices.

The problem is that the people in a shop develop certain habits, and come to certain shared understandings, and become quite comfortable in that. They experience "confirmation bias", in which their experiences confirm their bad practices ("I wrote that really quick and dirty, and we still shipped on time!") and discount evidence that contradicts their beliefs ("I spent three weeks on that bug, but I'm moving on to new code now.")

My experience is that the shops with bad practices are particularly resistant to good practices. The reason the shop settled on bad practices in the first place is that they weren't interested in alternatives.

On the other extreme, I've worked in shops that were so smart, and so open to new ideas, that it got kind of crazy because the infrastructure was so dynamic even from week to week, it was hard to tell how to write code and get it released (I'm currently in a situation where I've been waiting a month for a QA box, but they just re-engineered their code check-in workflow, so I'm back to square one, with no QA box. Or maybe square -1.)

As you stay with a shop, and as you gain responsibility, you'll have more and more influence on the culture. After all, the guy sitting at the keyboard ultimately makes a lot of the decisions. But it will be a long process of identifying specific things that could be improved, and either changing them individually yourself, or educating and persuading others to follow a better way.

...

...or, I should add, moving to a different shop. In this industry, sometimes the grass really is markedly greener on the other side.


问:
Unit testing statically loaded data
Scenario: I have a configuration file containing some structured data that is loaded in at runtime and is not modified by the application, but is referenced in many places.  There are functions that retrieve specific data from the configuration file (after it's been loaded into memory).

I'd like to write unit tests that ensure that data has not been changed inadvertently by a developer, is this good practice or overkill?

E.g. Assert(GetDataForKey("SomeKey") == "MyValue")

答:
A configuration file is part of the configuration of the application. As such, you can test it in a couple of ways.

One way is to reference your version control system and see if the file is identical to what should have been deployed. You can short cut this process by creating a separate file with a hash (what is called a digest) of the configuration file and comparing the expected digest with the actual digest.

You can also set up an automatic review of your configuration using Tripwire or similar applications.

Title: Unit testing statically loaded data


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
I can't find the right post anymore, but Eric Lippert (and possibly several other softies) have opined on several occasions about how Linq is declarative, which, for several classes of problems, is far more intuitive than imperative syntax.

Linq enables you to write code that expresses the intent, not the mechanism.

You tell me which is easier to read.  This:

IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    List<Customer> results = new List<Customer>();
    foreach (Customer c in source)
    {
        if (c.FirstName == "Aaron")
        {
            results.Add(c);
        }
    }
    results.Sort(new LastNameComparer());
    return results;
}

class LastNameComparer : IComparer<Customer>
{
    public int Compare(Customer a, Customer b)
    {
        return x.LastName.CompareTo(b.LastName);
    }
}
```

<p>Or this?</p>

<pre class="lang-cs prettyprint-override"><code>IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    return from c in source
           where c.FirstName == "Aaron"
           orderby c.LastName
           select c;
}
</code>```

Or even this?

IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    return source.Where(c => c.FirstName == "Aaron").OrderBy(c => c.LastName);
}
```

The first example is just a bunch of pointless boilerplate in order to obtain the simplest of results.  Anybody who thinks that it is more readable than the Linq versions needs to have his head examined.  Not only that, but the first one wastes memory.  You can't even write it using yield return because of the sorting.

Your coworker can say what he wants; personally, I think Linq has improved my code readability immeasurably.

There's nothing "relational" about Linq either.  It may have some superficial similarities to SQL but it does not attempt in any shape or form to implement relational calculus.  It's just a bunch of extensions that make it easier to query and project sequences.  "Query" does not mean "relational", and there are in fact several non-relational databases that use SQL-like syntax.  Linq is purely object-oriented, it just happens to work with relational databases through frameworks such as Linq to SQL because of some expression tree voodoo and clever design from the C# team, making anonymous functions implicitly convertible to expression trees.

Body:
I can't find the right post anymore, but Eric Lippert (and possibly several other softies) have opined on several occasions about how Linq is declarative, which, for several classes of problems, is far more intuitive than imperative syntax.

Linq enables you to write code that expresses the intent, not the mechanism.

You tell me which is easier to read.  This:

IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    List<Customer> results = new List<Customer>();
    foreach (Customer c in source)
    {
        if (c.FirstName == "Aaron")
        {
            results.Add(c);
        }
    }
    results.Sort(new LastNameComparer());
    return results;
}

class LastNameComparer : IComparer<Customer>
{
    public int Compare(Customer a, Customer b)
    {
        return x.LastName.CompareTo(b.LastName);
    }
}

Or this?

IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    return from c in source
           where c.FirstName == "Aaron"
           orderby c.LastName
           select c;
}

Or even this?

IEnumerable<Customer> GetVipCustomers(IEnumerable<Customer> source)
{
    return source.Where(c => c.FirstName == "Aaron").OrderBy(c => c.LastName);
}

The first example is just a bunch of pointless boilerplate in order to obtain the simplest of results.  Anybody who thinks that it is more readable than the Linq versions needs to have his head examined.  Not only that, but the first one wastes memory.  You can't even write it using yield return because of the sorting.

Your coworker can say what he wants; personally, I think Linq has improved my code readability immeasurably.

There's nothing "relational" about Linq either.  It may have some superficial similarities to SQL but it does not attempt in any shape or form to implement relational calculus.  It's just a bunch of extensions that make it easier to query and project sequences.  "Query" does not mean "relational", and there are in fact several non-relational databases that use SQL-like syntax.  Linq is purely object-oriented, it just happens to work with relational databases through frameworks such as Linq to SQL because of some expression tree voodoo and clever design from the C# team, making anonymous functions implicitly convertible to expression trees.


答:
I think it at least partly depends on the nature of your situation.

You mentioned constantly changing requirements. If the customer says "I want this bee-keeping application to also work with wasps" then that seems like the kind of situation in which careful design would help progress, not hinder it (especially when you consider that in the future she might want to keep fruit-flies too.)

On the other hand, if the nature of the change is more like "I want this bee-keeping application to manage the payroll of my laundromat conglomerate", no amount of code will dig you out of your hole.

There's nothing inherently good about design patterns. They're tools like any other - we only use them to make our jobs easier in the medium-to-long run. If a different tool (such as communication or research) is more useful then we use that.

Title: Should we avoid using design patterns in constantly changing projects?

Body:
A friend of mine is working for a small company on a project every developer would hate: he's pressured to release as quickly as possible, he's the only one who seem to care about technical debt, the customer has no technical background, etc.

He told me a story which made me think about the appropriateness of design patterns in projects like this one. Here's the story.

We had to display products at different places on the website. For example, content managers could view the products, but also the end users or the partners through the API.

Sometimes, information was missing from the products: for example, a bunch of them didn't have any price when the product was just created, but the price wasn't specified yet. Some didn't have a description (the description being a complex object with modification histories, localized content, etc.). Some were lacking shipment information.

Inspired by my recent readings about design patterns, I thought this was an excellent opportunity to use the magical Null Object pattern. So I did it, and everything was smooth and clean. One just had to call product.Price.ToString("c") to display the price, or product.Description.Current to show the description; no conditional stuff required. Until, one day, the stakeholder asked to display it differently in the API, by having a null in JSON. And also differently for content managers by showing "Price unspecified [Change]". And I had to murder my beloved Null Object pattern, because there was no need for it any longer.

In the same way, I had to remove a few abstract factories and a few builders, I ended up replacing my beautiful Facade pattern by direct and ugly calls, because the underlying interfaces changed twice per day for three months, and even the Singleton left me when the requirements told that the concerned object had to be different depending on the context.

More than three weeks of work consisted of adding design patterns, then tearing them apart one month later, and my code finally became spaghetti enough to be impossible to maintain by anyone, including myself. Wouldn't it be better to never use those patterns in the first place?

Indeed, I had to work myself on those types of projects where the requirements are changing constantly, and are dictated by persons who don't really have in mind the cohesion or the coherence of the product. In this context, it doesn't matter how agile you are, you'll come with an elegant solution to a problem, and when you finally implement it, you learn that the requirements changed so drastically, that your elegant solution doesn't fit any longer.

What would be the solution in this case?

Not using any design patterns, stop thinking, and write code directly?

It would be interesting to do an experience where a team is writing code directly, while another one is thinking twice before typing, taking the risk of having to throw away the original design a few days later: who knows, maybe both teams would have the same technical debt. In the absence of such data, I would only assert that it doesn't feel right to type code without prior thinking when working on a 20 man-month project.

Keep the design pattern which doesn't make sense any longer, and try to add more patterns for the newly created situation?

This doesn't seem right neither. Patterns are used to simplify the understanding of the code; put too much patterns, and the code will become a mess.

Start thinking of a new design which encompasses the new requirements, then slowly refactor the old design into the new one?

As a theoretician and the one who favors Agile, I'm totally into it. In practice, when you know that you'll have to get back to the whiteboard every week and redo the large part of the previous design and that the customer just doesn't have enough funds to pay you for that, nor enough time to wait, this probably won't work.

So, any suggestions?


问:
Organizing solution / project structure and classes for Line of Business Application (LOB)
The question how-do-you-organize-your-projects already has a few good answers. I would like to get a better understanding about this suggested structure:

```<code>MyApp.Core
MyApp.Model
MyApp.Presenter
MyApp.Persistence
MyApp.UI
MyApp.Validation
MyApp.Report
MyApp.Web
</code>```

Assuming MyApp is a winforms rich client to administer students, courses, rooms and teachers

Lets say i have a winforms user control to edit course information (name of the course, who teaches it, in  which room and which students did register for the course). The class below reflects all the information i need for the user control

```<code>public class CourseDetails{
    public int Id{ get; set;}
    public Course Course{ get; set;}
    public Teacher Teacher{get; set;}
    public Room Room{get; set;}
    public List<Student> StudentList{get; set;}
}
</code>```

Where would you put this class?

Methods of MyApp.Model

I would like to know how complex or simple the classes inside the namespace MyApp.Model shoud be.

Should the project MyApp.Model only contain very simple classes like

```<code>public class Course{
    public int CourseId{ get; set;}
    public string CourseName{ get; set;}
    public int CategoryId {get; private set;}

}
public class Teacher{
    public int TeacherId{ get; set;}
    public string TeacherName{ get; set;}
}
</code>```

or should MyApp.Model contain also

complex classes like CourseDetails

additional methods for each class like Save() or GetById() ?

Additional topics

Where (in which project) should interfaces be implemented and where should base classe be used.

When should this additional methods (Save(), GetById()) be inherited from a base class or be contained in the class which implents an interface that has all the methods for saving and selecting.

```<code>public class CourseDetails: ModelBase{
    ...
}

public class ModelBase{
    public bool Save() {
        Console.WriteLine("do something clever to save each entity");
        return true;
    }
}
</code>```

Sorry for not beeing more clear; I would like to understand what kind of things (classes, interfaces, ressources, etc) should be put in which project and why. I hope you get the idea.

答:
It Depends

The answer for this of course depends on several factors:

will any of the project binaries be shared across applications?

will any of the project binaries be pluggable?

does the application have multiple tiers?

If the application is stand-alone, the best option may be to have a single, self-contained exe, as it provides an extremely simple and easy deployment model - xcopy.  In this case, organization of files is done through folders inside a single project.

This sounds in-line with your application description, assuming that the web portion is composed of client code meant to interface with a separate data store for the class administration data.

In a multi-tier application, you may need 1+ binaries for each tier and additional binaries for any types shared across tiers.

In general, though, I wouldn't split up projects unless there is a need to - YAGNI.


问:
Object Design & Cohesion - Issue & potential refactoring
Abstract

I have been trying to get my head around the cohesiveness of some functionality in our code base.  I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle.

Issue

The problem domain is a Well, otherwise known as a round hole in the ground.  The current code looks something like this...  I have a set of data in a data only object...

Note: This is not the full code, just method names to keep things short...

```<code>public class WellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }
}
</code>```

I broke functionality that operates on this data into several small classes. As per below…

```<code>public class ReferenceWellSurvey
{
   ICollection<SurveyPointCalculate> _calculatedSurveyPoints;
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
}

public class ReferenceWellGeometry
{
   ICollection<GeometryItem> _geometryItems;
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
}

public class ReferenceWellTemperature
{
   ICollection<TemperaturePoint> _wellTemperatures;
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
Etc.
</code>```

I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic.  Something like….

```<code>public class ReferenceWellData
{
private IReferenceWellGeometry _refWellGeometry;
private IReferenceWellTemperature _refWellGeometry;
          private IReferenceWell _refWellGeometry;
          private IReferenceFluid _refWellFluid;
       //Proxy functions from each class to glue it all back together…
}
</code>```

A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data.  At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together.  Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth().  Really what I did didn’t solve this issue.

After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins.

•   Anemic domain model

•   Low cohesion

•   Constructor over injection in code where I try to glue things together

•   Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle.

Solution

I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.

My current thoughts on fixing this are as follows.  Move the functionality that operates on the well data into the same class.  This should help get this functionality closer to Communicational/informational cohesion.

```<code>public class WellData : IWellData
{
    public string Name { get; set; }
    public ICollection<SurveyPoint> SurveyPoints { get; set; }
    public ICollection<GeometryItem> GeometryItems { get; set; }
    public ICollection<TemperaturePoint> WellTemperature { get; set; }
    public ICollection<FluidPoint> WellFluids { get; set; }

   // Operates on SurveyPoint collection
   double GetTvdAtDepth(double depth) {}
   double GetAzimuthAtDepthRad(double depth) {}
   double GetInclinationAtDepthRad(double depth){}
   double GetTortuosityPeriodAtDepth(double  depth ) {}
   double GetTortuosityAmplitudeAtDepth(double depth ) {}
   //Operates on WellGeometry collection
   double GetFrictionAtDepth(double depth) {}
   double GetHoleIdAtDepth(double depth) {}
   //Operates on WellTemperature collection
   double GetTemperatureAtDepth(double depth) {}
   double GetSurfaceTemperature(double depth) {}
}
</code>```

Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth.  In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class.

Thoughts on this approach vs. the original approach?  One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...

答:
Start with deeply defining your classes instead of a Uber-Interface obstruction abstraction.

I think of it as defining my "oil well domain" data structures.

The idea is to discover the bits that have independent/discrete meaning. As the class definitions evolve, extract parts that can in their own right be classes. Then composite as needed later. You always edit classes as things develop. This approach should allow us to evolve higher-level classes that address cross-cutting concerns.

Is a ReferenceWell a Well or a derived Well? Static or "reference" data/state makes it just another Well.

HoleID uniquely identifies a Well object

Could this be what a SurveyPoint is?

```<code>public class SurveyPoint
{
    // Each property is typed. This is intentional.
    // It gives us a place to encapsulate properties and
    // behaviors/methods that are "atomic" to each.

    public int              HoleID      { get; set; }
    public Geometry         Geometry    {get; set;}
    public Depth            Depth       {get; set;}
    public TemperaturePoint Temperature { get; set; }
    public Inclination      Inclination { get; set; }
    public Tortousity       Torture     { get; set; }
    public Asmuth           Asmuth      { get; set; }
    public Tvd              Tvd         { get; set; }
}
</code>```

And then TemperaturePoint, FluidPoint, GeometryItem, etc. are just subsets (not sub classes) of a SurveyPoint? In other words, different aspects. So..

```<code>public class SurveyPoint
{
    //. . .

    public Temperature GetTemperature() {return this.Temperature;}
    public FluidPoint GetFluidPoint () {return this.FluidPoint;}
    // etc. and overload as needed.
}

public class SurveyPointCollection : Collection<SurveyPoint> {
    public TemperatureCollection GetTemperatures() {}
    public FluidPointCollection GetFluidPoints() {}

    public GetTemperature(Depth depth) {
       // iterate collection to find the SurveyPoint with that depth
     }
    //etc.
}

public class Temperature {
    public HoleID {get; set;}
    public double Temperature {get; set;}
    // any other properties help *define* a temperature for a well

    // add any useful methods that operate only on properties defined in this class
}

// a similar class for each of the other SurveyPoint aspects.
</code>```

I see one aspect of cohesion evolving and revolving around the core data structures. Once the data classes are described in (enough) detail then you can begin to "map" behavior to appropriate levels of the data encapsulations thus making very cohesive Object Oriented classes (yes @FrankHileman is correct, you are thinking functionally not Objectively).

Then I assume a Well might start looking like this

```<code>public class Well
{
    public string Name {get; set;}
    public int HoleID {get; set;}
    public SurveyPointCollection SurveyPoints {get; set;}

    public Well () { }

    public TemperatureCollection GetTemperatures () {
         SurveyPoints.GetTemperatures();
    }

    public Temperature GetTemperature ( Depth depth ) { }

    // etc. for all other aspects.

}
</code>```

Exploring the Behavior Aspects

```<code>public class Surveyer
{
    protected Well MyWell { get; set; }
    protected DepthCalculator Calculator { get; set; }

    public Surveyer ( Well theWell ) {
        MyWell = theWell;
        Calculator = new DepthCalculator (MyWell.GetSurveyPoints());
    }
}
</code>```

"Depth" seems to be the unifying thing in the ReferenceWellSurvey method names so I imagined a DepthCalculator. However we may very well have calculation that corresponds to our various data aspects. So we might have this:

```<code>public class DepthCalculator {
    protected TemperatureCalculator {get; set;}
    protected InclinationCalculator {get; set;}
    protected FrictionCalculator    {get; set;}
    // etc.

    public DepthCalculator (SurveyPointCollection dataPoints) {
        TemperatureCalculator = new TemperatureCalculator (dataPoints.GetTemperatures());
        FrictionCalculator = new FrictionCalculator(dataPoints.GetFrictionPoints());
    }
}
</code>```

I don't know enough about the "oil well domain" to know where to go with this. However you might look at the Builder Pattern for inspiration.

Body:
Start with deeply defining your classes instead of a Uber-Interface obstruction abstraction.

I think of it as defining my "oil well domain" data structures.

The idea is to discover the bits that have independent/discrete meaning. As the class definitions evolve, extract parts that can in their own right be classes. Then composite as needed later. You always edit classes as things develop. This approach should allow us to evolve higher-level classes that address cross-cutting concerns.

Is a ReferenceWell a Well or a derived Well? Static or "reference" data/state makes it just another Well.

HoleID uniquely identifies a Well object

Could this be what a SurveyPoint is?

public class SurveyPoint
{
    // Each property is typed. This is intentional.
    // It gives us a place to encapsulate properties and
    // behaviors/methods that are "atomic" to each.

    public int              HoleID      { get; set; }
    public Geometry         Geometry    {get; set;}
    public Depth            Depth       {get; set;}
    public TemperaturePoint Temperature { get; set; }
    public Inclination      Inclination { get; set; }
    public Tortousity       Torture     { get; set; }
    public Asmuth           Asmuth      { get; set; }
    public Tvd              Tvd         { get; set; }
}

And then TemperaturePoint, FluidPoint, GeometryItem, etc. are just subsets (not sub classes) of a SurveyPoint? In other words, different aspects. So..

public class SurveyPoint
{
    //. . .

    public Temperature GetTemperature() {return this.Temperature;}
    public FluidPoint GetFluidPoint () {return this.FluidPoint;}
    // etc. and overload as needed.
}

public class SurveyPointCollection : Collection<SurveyPoint> {
    public TemperatureCollection GetTemperatures() {}
    public FluidPointCollection GetFluidPoints() {}

    public GetTemperature(Depth depth) {
       // iterate collection to find the SurveyPoint with that depth
     }
    //etc.
}

public class Temperature {
    public HoleID {get; set;}
    public double Temperature {get; set;}
    // any other properties help *define* a temperature for a well

    // add any useful methods that operate only on properties defined in this class
}

// a similar class for each of the other SurveyPoint aspects.

I see one aspect of cohesion evolving and revolving around the core data structures. Once the data classes are described in (enough) detail then you can begin to "map" behavior to appropriate levels of the data encapsulations thus making very cohesive Object Oriented classes (yes @FrankHileman is correct, you are thinking functionally not Objectively).

Then I assume a Well might start looking like this

public class Well
{
    public string Name {get; set;}
    public int HoleID {get; set;}
    public SurveyPointCollection SurveyPoints {get; set;}

    public Well () { }

    public TemperatureCollection GetTemperatures () {
         SurveyPoints.GetTemperatures();
    }

    public Temperature GetTemperature ( Depth depth ) { }

    // etc. for all other aspects.

}

Exploring the Behavior Aspects

public class Surveyer
{
    protected Well MyWell { get; set; }
    protected DepthCalculator Calculator { get; set; }

    public Surveyer ( Well theWell ) {
        MyWell = theWell;
        Calculator = new DepthCalculator (MyWell.GetSurveyPoints());
    }
}

"Depth" seems to be the unifying thing in the ReferenceWellSurvey method names so I imagined a DepthCalculator. However we may very well have calculation that corresponds to our various data aspects. So we might have this:

public class DepthCalculator {
    protected TemperatureCalculator {get; set;}
    protected InclinationCalculator {get; set;}
    protected FrictionCalculator    {get; set;}
    // etc.

    public DepthCalculator (SurveyPointCollection dataPoints) {
        TemperatureCalculator = new TemperatureCalculator (dataPoints.GetTemperatures());
        FrictionCalculator = new FrictionCalculator(dataPoints.GetFrictionPoints());
    }
}

I don't know enough about the "oil well domain" to know where to go with this. However you might look at the Builder Pattern for inspiration.