问:
UML Class Diagram: How can I represent "orthogonal" generalizations (or multi-inheritence)?
I try to represent in a UML Class Diagram the following object and features:

The Object: A System (e.g. an electronic device) that can be of Type A, B or C

If the System is of type A, it has a specific extra attribute (let say "sub-type", which values can be A1 or A2)

I created a Class named "System" and:

Created a class "System_TypeA" that holds an extra attribute named "subSystem" that can take any value within A1 and A2.

Created a generalization relationship beteween the two classes ("System_TypeA" is a "System")

So far, so good.

Now, each System can be the backup system of other Systems. If this is the case, the System should hold a collection of references of the systems it is backing-up

So for this feature, I also created a Class named "Backup_System" and created generalization between the two classes, since a "Backup_System" is a "System".

So how to represent in the Class Diagram the fact that there can be Systems of Type A that are Backup systems (i.e. the problem of multiple inheritance)??

(For info, the implementation should be done in java, so the same problem of multi-inheritance will be faced at implementation.)

答:
Your question contains two issues: (1) the general issue of multiple inheritance and multiple classification; (2) the question of how to model backup systems in a conceptual model. I'll try to explain (1) while (2) has been addressed by some other answers already (and indeed, you really need to associate your backup systems with the systems they are supposed to back up).

UML does not have any problem with multiple inheritance, just Java (and many other OO languages) do have a problem with it. In the UML class diagram you just connect your subclass TypeA_Backup_System with the two superclasses TypeA_System and Backup_System using generalization arrows.

However, you may not really want to add a class TypeA_Backup_System, but rather you may mean the (related) issue that you may have specific systems (instances of System) that instantiate both TypeA_System and Backup_System. This is multiple classification, again not supported by Java. For allowing multiple classification in a UML class diagram, you just do not add the constraint keyword disjoint to your generalization arrows, then, by default, the subclasses may overlap, implying the possibility of multiple classification.

OwnerDisplayName: gwag


答:
Not quite sure if I understand your question. I think you just have a composition relationship of system to system (see diagram). A system can backup another system.

I don't think you need to look at multiple inheritance here. It's possible to overdo things with inheritance. Try to use composition instead when you can.

ContentLicense: CC BY-SA 3.0

Title: UML Class Diagram: How can I represent "orthogonal" generalizations (or multi-inheritence)?

Body:
I try to represent in a UML Class Diagram the following object and features:

The Object: A System (e.g. an electronic device) that can be of Type A, B or C

If the System is of type A, it has a specific extra attribute (let say "sub-type", which values can be A1 or A2)

I created a Class named "System" and:

Created a class "System_TypeA" that holds an extra attribute named "subSystem" that can take any value within A1 and A2.

Created a generalization relationship beteween the two classes ("System_TypeA" is a "System")

So far, so good.

Now, each System can be the backup system of other Systems. If this is the case, the System should hold a collection of references of the systems it is backing-up

So for this feature, I also created a Class named "Backup_System" and created generalization between the two classes, since a "Backup_System" is a "System".

So how to represent in the Class Diagram the fact that there can be Systems of Type A that are Backup systems (i.e. the problem of multiple inheritance)??

(For info, the implementation should be done in java, so the same problem of multi-inheritance will be faced at implementation.)

OwnerDisplayName: Oliver Watkins


答:
Since

each System can be the backup system of other Systems

do you really need a "Backup_system" class? Shouldn't be an association?

Like this

(click on the image to copy)

OwnerDisplayName: Xaelis


问:
Choosing a class abstraction when multiple viable approaches exist
I'm having trouble trying to design a class structure for some search functionality.  It's quite possible that I'm approaching this incorrectly altogether, but putting that aside I'm curious how other people would approach a situation as follows:

We need search functionality that allows users to access parcel information:

People will be able to search via 3 different search methods -- MethodA, MethodB, MethodC.

(To give some perspective on what I mean by "method", lets think of these as things like a one line search that will do some intelligent parsing, another method has specific form fields for entering each parameter, etc.)

People will be able to search via 3 different search types -- TypeA, TypeB, TypeC.
(For example, search by owner, search by parcel address, etc.)

The situation isn't terribly complex, but what I'm stuck on is whether I should design my classes around an abstract method object, or an abstract type object.  Essentially, should I do this:

```<code>public class ConcreteMethodA : BaseMethod
{
  public ReturnDataType GetResultsTypeA(){};
  public ReturnDataType GetResultsTypeB(){};
  //Etc.
}
</code>```

Or this:

```<code>public class ConcreteTypeA : BaseType
{
  public ReturnDataType GetResultsMethodA(){};
  public ReturnDataType GetResultsMethodB(){};
  //Etc.
}
</code>```

If you do have some advice about how to solve my specific scenario, I will certainly appreciate it.  However, I'm more interested in heuristics for approaching a design problem of this nature.

答:
I do not know, if I am getting you right, but as far as I understand, you have the following scenario:

1) You have different kinds of querying:

search by owner

search by destination address
...

2) Each of which has e.g different sources or whatever

So the best way to solve this would be via strategy.
Defining the allowed queries in an interface (supposing you were writing C#):

```<code>interface IQueryMechanism
{
   Result SearchByOwner(string owner);
   ...
}
</code>```

Then defining a Service which takes care of the ingoing calls.

```<code>public class ParcelService
{
    IQueryMechanism mechanism;

    public void setQueryMechanism(IQueryMechanism mechanism) { this.mechanism=mechanism; }
    public SearchByOwner(string owner) { return mechanism.SearchByOwner(string owner);}
}
</code>```

When you instantiate the ParcelService you could inject the appropriate mechanism via setter injection (for readability reasons I left guarding clauses out). So everytime a request comes in, the repository delegates this request to the underlying mechanism.

And your mechanism-class looks like

```<code>public class OnlineSearch : IQueryMechanism
{
    public SearchByOwner(string owner) { /* business logic here */}
    ...
}
</code>```

So you instantiate one Service and swap at runtime, the QueryMechanism.

Body:
I do not know, if I am getting you right, but as far as I understand, you have the following scenario:

1) You have different kinds of querying:

search by owner

search by destination address
...

2) Each of which has e.g different sources or whatever

So the best way to solve this would be via strategy.
Defining the allowed queries in an interface (supposing you were writing C#):

interface IQueryMechanism
{
   Result SearchByOwner(string owner);
   ...
}

Then defining a Service which takes care of the ingoing calls.

public class ParcelService
{
    IQueryMechanism mechanism;

    public void setQueryMechanism(IQueryMechanism mechanism) { this.mechanism=mechanism; }
    public SearchByOwner(string owner) { return mechanism.SearchByOwner(string owner);}
}

When you instantiate the ParcelService you could inject the appropriate mechanism via setter injection (for readability reasons I left guarding clauses out). So everytime a request comes in, the repository delegates this request to the underlying mechanism.

And your mechanism-class looks like

public class OnlineSearch : IQueryMechanism
{
    public SearchByOwner(string owner) { /* business logic here */}
    ...
}

So you instantiate one Service and swap at runtime, the QueryMechanism.


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
I see two problems with operator overloading.

Overloading changes the semantics of the operator, even if that is not intended by the programmer. For example, when you overload &&, || or ,, you lose the sequence points that are implied by the built-in variants of these operators (as well as the short-circuiting behaviour of the logical operators). For this reason, it is better not to overload these operators, even if the language allows it.

Some people see operator overloading as such a nice feature, they start to use it everywhere, even if it is not the appropriate solution. This causes other people to over-react in the other direction and warn against the use of operator overloading.
I don't agree with either group, but take the middle ground: Operator overloading should be used sparingly and only when

the overloaded operator has the natural meaning for both the domain experts and the software experts. If those two groups do not agree on the natural meaning for the operator, don't overload it.

for the type(s) involved, there is no natural meaning for the operator and the immediate context (preferably same expression, but no more than a few lines) always makes it clear what the meaning is of the operator. An example of this category would be operator<< for streams.

ContentLicense: CC BY-SA 2.5


问:
Difference between USP and IEEE rounding
I am trying to understand the difference between different rounding methods: Our application offers two different types of rounding:

IEEE

USP (GMP) rounding. http://www.usp.org/sites/default/files/usp_pdf/EN/USPNF/USP34-NF29General%20Notices.pdf

In our unit tests, they seem to do the same thing for the cases being tested. However, I haven't found anyone in the office who can explain what is meant when selecting rounding mode of IEEE

答: According to wikipedia, IEEE 754 specifies round to even when the next digit is a 5, while the paper you cite says that a digit of 5 means add one to the preceding digit.</p>


答:
Both approaches are right, either overriding a method, or subclassing.
By "right", I mean, you can craft a program that works, with either approach.

Yet I suggest to take the a class definition for each search, it's more flexible.

You can add properties, and replace the "Search" method, and add more search ways, just by adding classes. It seems a little complicated first, but, in real world, makes your application easier to extend.

Also, split each search method, in an specific class.

```<code>public abstract class SingleSearchClass : Object
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */ class QuickSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */class HeuristicsSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */ class RandomSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}
</code>```

And declare a wrapper / adapter, that let the user choose the different available search methods:

```<code>public enum SearchMethodEnum
{
  NoSearch,
  QuickSearch,
  HeuristicsSearch,
  RandomSearch,
}

public /* concrete */ class SearchClientClass : Object
{
  public /* property*/ SearchMethodEnum SearchMethod
    { get; set; }

  public /* property*/ Object Params
    { get; set; }

  public ReturnDataType Execute()
  {
    ReturnDataType Result = null;

      if (this.SearchMethod != SearchMethodEnum.NoSearch)
      {
        SingleSearchClass Search = null;

        switch (this.SearchMethod)
        {
          case SearchMethodEnum.QuickSearch:
            Search = new SearchClientClass();
          break;

          case SearchMethodEnum.HeuristicsSearch:
            Search = new HeuristicsSearchClass ();
          break;

          case SearchMethodEnum.RandomSearch:
            Search = new RandomSearchClass ();
          break;
        } // switch

        Result = Search.Search(this.Params);
      } // if

    return Result;
  }
} // class SearchClientClass
</code>```

And, a generic example (pseudocode):

```<code>public /* concrete */ class SearchExampleClass
{
  public static void main(string[] args)
  {
    SearchClientClass Client = new SearchClientClass();

    Client.Params = "John Doe";
    Client.SearchMethod = SearchMethodEnum.QuickSearch;

    ReturnDataType Result = Client.Execute();

    Client = null;
  }

}
</code>```

[UPDATE] Extend description.

Just my 2 cents.

Title: Choosing a class abstraction when multiple viable approaches exist

Body:
I'm having trouble trying to design a class structure for some search functionality.  It's quite possible that I'm approaching this incorrectly altogether, but putting that aside I'm curious how other people would approach a situation as follows:

We need search functionality that allows users to access parcel information:

People will be able to search via 3 different search methods -- MethodA, MethodB, MethodC.

(To give some perspective on what I mean by "method", lets think of these as things like a one line search that will do some intelligent parsing, another method has specific form fields for entering each parameter, etc.)

People will be able to search via 3 different search types -- TypeA, TypeB, TypeC.
(For example, search by owner, search by parcel address, etc.)

The situation isn't terribly complex, but what I'm stuck on is whether I should design my classes around an abstract method object, or an abstract type object.  Essentially, should I do this:

```<code>public class ConcreteMethodA : BaseMethod
{
  public ReturnDataType GetResultsTypeA(){};
  public ReturnDataType GetResultsTypeB(){};
  //Etc.
}
</code>```

Or this:

```<code>public class ConcreteTypeA : BaseType
{
  public ReturnDataType GetResultsMethodA(){};
  public ReturnDataType GetResultsMethodB(){};
  //Etc.
}
</code>```

If you do have some advice about how to solve my specific scenario, I will certainly appreciate it.  However, I'm more interested in heuristics for approaching a design problem of this nature.

Body:
Both approaches are right, either overriding a method, or subclassing.
By "right", I mean, you can craft a program that works, with either approach.

Yet I suggest to take the a class definition for each search, it's more flexible.

You can add properties, and replace the "Search" method, and add more search ways, just by adding classes. It seems a little complicated first, but, in real world, makes your application easier to extend.

Also, split each search method, in an specific class.

public abstract class SingleSearchClass : Object
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */ class QuickSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */class HeuristicsSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}

public /* concrete */ class RandomSearchClass : SearchAbstractClass
{
  public ReturnDataType Search(Object SomeParameters){};
}

And declare a wrapper / adapter, that let the user choose the different available search methods:

public enum SearchMethodEnum
{
  NoSearch,
  QuickSearch,
  HeuristicsSearch,
  RandomSearch,
}

public /* concrete */ class SearchClientClass : Object
{
  public /* property*/ SearchMethodEnum SearchMethod
    { get; set; }

  public /* property*/ Object Params
    { get; set; }

  public ReturnDataType Execute()
  {
    ReturnDataType Result = null;

      if (this.SearchMethod != SearchMethodEnum.NoSearch)
      {
        SingleSearchClass Search = null;

        switch (this.SearchMethod)
        {
          case SearchMethodEnum.QuickSearch:
            Search = new SearchClientClass();
          break;

          case SearchMethodEnum.HeuristicsSearch:
            Search = new HeuristicsSearchClass ();
          break;

          case SearchMethodEnum.RandomSearch:
            Search = new RandomSearchClass ();
          break;
        } // switch

        Result = Search.Search(this.Params);
      } // if

    return Result;
  }
} // class SearchClientClass

And, a generic example (pseudocode):

public /* concrete */ class SearchExampleClass
{
  public static void main(string[] args)
  {
    SearchClientClass Client = new SearchClientClass();

    Client.Params = "John Doe";
    Client.SearchMethod = SearchMethodEnum.QuickSearch;

    ReturnDataType Result = Client.Execute();

    Client = null;
  }

}

[UPDATE] Extend description.

Just my 2 cents.


答:
I haven't fully figured it out. However, I know enough to keep working. IEEE rounding has 5 different modes. http://en.wikipedia.org/wiki/IEEE_floating_point#Rounding_rules

In our application, we are using C#'s default method, Math.round() which uses MidpointRounding.ToEven, that is, 4.5 rounds to 4 and 5.5 rounds to 6. So when our applications says IEEE rounding, they mean  http://en.wikipedia.org/wiki/Rounding#Round_half_to_even

Title: Difference between USP and IEEE rounding

Body:
I am trying to understand the difference between different rounding methods: Our application offers two different types of rounding:

IEEE

USP (GMP) rounding. http://www.usp.org/sites/default/files/usp_pdf/EN/USPNF/USP34-NF29General%20Notices.pdf

In our unit tests, they seem to do the same thing for the cases being tested. However, I haven't found anyone in the office who can explain what is meant when selecting rounding mode of IEEE


问:
Omitting "destructors" in C is taking YAGNI too far?
I'm working on a medium embedded application in C using OO-like techniques. My "classes" are .h/.c modules using data structs and function pointers structs to emulate encapsulation, polymorphism, and dependency injection.

Now, one would expect a myModule_create(void) function to come with a myModule_destroy(pointer) counterpart. But the project being embedded, the resources that are instantiated realistically should never be released.

I mean, if I have 4 UART serial ports and I create 4 UART instances with their required pins and settings, there's absolutely no reason to ever want to destroy UART #2 at some point during runtime.

So following the YAGNI (You ain't gonna need it) principle, should I omit the destructors? This seem extremely strange to me but I can't think of a use for them; resources are freed when the device powers-off.

答:
In my development, which makes extensive use of opaque data types to foster an OO-like approach, I too wrestled with this question. At first, I was decidedly in the camp of eliminating the destructor from the YAGNI perspective, as well as the MISRA "dead code" perspective. (I had plenty of resource room, that wasn't a consideration.)

However... the lack of a destructor can make testing more difficult, as in automated unit/integration testing. Conventionally, each test should support a setup/teardown so that objects can be created, manipulated, then destroyed. They are destroyed in order to assure a clean, untainted starting point for thenext test. To do this, the class needs a destructor.

Therefore, in my experience, the "aint't" in YAGNI turns out be to an "are" and I ended up creating destructors for every class whether I thought I'd need it or not. Even if I skipped testing, at least a correctly designed destructor exists for the poor slob that follows me will have one. (And, to a much lesser value, it makes the code more reusable in that it can be used in an environment where it would be destroyed.)

While that addresses YAGNI, it does not address dead code. For that, I find that a conditional compile macro something like #define BUILD_FOR_TESTING allows the destructor to be eliminated from the final production build.

Doing it this way: you have destructor for testing/future reuse, and you satisfy the design objectives of YAGNI and "no dead code" rules.


问:
Should you ever use private on fields and methods in C#?
I am somewhat new to C# and just found out that: in C# all of the fields and methods in a class are default private. Meaning that this:

```<code>class MyClass
{

string myString

}
</code>```

is the same as:

```<code>class MyClass
{

private string myString

}
</code>```

So because they are the same should I ever use the keyword private on fields and methods? Many online code samples use the keyword private in their code, why is that?

答:
Question:

"Should you ever use private on fields and methods in C#?"

Quick Answer:

Yes, but, it depends in your code logic.

Long Boring Extended Answer:

I suggest, always specify vissibility for members.

I think It is a good approach to declare members, by default, as "private".

In real world, I use "protected", instead.

Sooner, or later, that hidden member, could be used by a subclass.

Sometimes, a good question, can be better answered, by asking the opposite question.

The opposite question, to your question, could be something like:

"Should I use always public access modifier on fields & methods in C#"

In other programming languages you can "promote" protected to public,
depending on your design.

I use a lot of (visual) control deep hierarchy libraries, where,
some members (properties, methos) are required.

Sometimes, is better to have them public, sometimes don't.


问:
Why does Microsoft still ship VBA within Office products, instead of integrating .NET directly?
I know that it's possible to call .NET code from your VBA code, but why does VBA continue to exist? The only reason I can think about is legacy.

I just had to sort a Scripting.Dictionary and the amount of code needed was frightening.

The IDE looks like Visual Studio 2003. And there are many little details, that drive you insane (Like changing the line, and getting a warning because of some compilation error). Or, if you open more than one spreadsheet, it mixes into you "VBAProject" and this is really confusing.

The whole module/classmodule/form division is actually not that bad, but I end up everytime with directly writing logic in forms, or having one huge module that handles everything.

Why can't I press Alt+F11, and hack in C#?

答:
If you consider the main reason people buy Office is to keep compatibility with all the existing documents, many of which have macros and VBA in them, it would be a very brave Microsoft to treat those users like they did the VB6 crowd and tell them to suck it up and start coding in .NET, just take a look at the #1 uservoice request ever!

I imagine the LibreOffice guys would cheer themselves into unconsciousness though!

VBA is for productivity in Office, not "programming". The day you need more power from your documents is the day you hire a programmer to rewrite everything. I guess another reason is why Visual Studios macros are not .NET either - think of the devenv4 COM object as not much different to VBA.


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
Recursion is a function that calls itself.

How to use it, when to use it and how to avoid bad design are important to know, which requires you to try it out for yourself, and understand what happens.

The most important thing you need to know is to be very careful to not get a loop that never ends. The answer from pramodc84 to your question has this fault: It never ends...

A recursive function must always check for a condition to determine if it should call itself again or not.

The most classic example to use recursion, is to work with a tree with no static limits in depth. This is a task that you must use recursion.

Title: In plain English, what is recursion?


问:
AngularJS Directive vs Service vs Controller
I am about to start implementing a change request on my companies internal website, that will check a bunch of fields and highlight them if they match certain guidelines.  For example, if the date of birth is today, that field will be outlined and the tooltip will say "Wish them a happy birthday!".

The specs ask for this to be loaded after the rest of the page is done rendering, so it won't increase the load time. Since I am new to angularJS, I'm not sure of the 'proper' ways this should be done.

Issues:

Since this includes adding borders and images and title attributes (DOM manipulation), it seems I should be using a directive.

However, this won't be reusable or 'short' like most directives seem to be.

Half of the data I need to check will be returned in the original call on page load, so I would like to save that and not waste another call getting it again, which makes me think a service would be nice for storing all that data.

I do know how to do this all in the controller, but that is bad bad code :P

Any ideas on the best way this could be done? Basically, I will need an http call to check all the data, which will return an object with bool values for each type of 'Call Out' I need to do. Then I'll run through this list and if the value is true, add a border, image, and tooltip text.

I'm not sure if this question is clear enough, so if you want me to add some details, please ask. Thank you!

答:
You're right, there's many options at play.

A controller is a good place to start writing something new in angular. Tying a controller to a piece of markup lets you use angular's already existing library of directives with angular's existing services.

After a very short while of living with this, you'll realize your controller has gotten too large. Well now its time to refactor. Here's the general guidelines I tend to follow.

Controllers: controllers attach and manage values/functionality tied to the $scope. Ultimately $scope tends to be heavily presentation driven. IE its a view model.

Services: services tend to tie in infrastructure, backend, or other browser features

Directives: directives allow you to integrate with DOM events/functionality not handled by existing handlers.

So you'll want to push code in one of three directions:

Code from my controller is really logically another piece of presentation data/logic and should be split into another controller. Note when working with items on $scope, its best to segregate parts that each controller is responsible for into their own objects on $scope. For example $scope.creditCard.[blah] for one controller vs $scope.billingAddress.[blah] for another controller. This helps prevent issues with angular's use of prototype inheritance on $scope.

Code from my controller is a piece of application infrastructure or utility code, that may need to be shared through the app, and should be split off into a service

Code from my controller is concerned heavily with presentation/DOM organization, and therefore should be split off into its own directive

An example of 1. might be to handle entering/validating credit card separate from the rest of the payment form. You'd have a bunch of credit card logic in a controller separate from the logic for letting users input addresses, so they'd be logically separate controllers.

An example of 2 might be to move the part that communicates with the credit card backend service to accept/decline payment. Or another example might be a module that talks to the backend to handle the user creation API.

An example of 3 might be to create some sort of auto-tab functionality that moves the cursor between the 4 edit boxes after the 4 numbers are entered for a credit card.

Split up your app accordingly.


答:
Yes you should use it : ) The private keyword is used because it is generally accepted practice and removes all doubt about the intended scope of a class member.

Readability is very important with code, especially when working in a team.  If you want to look at code readability further, a good reference book I can recommend is The Elements of C# Style.

Title: Should you ever use private on fields and methods in C#?

Body:
I am somewhat new to C# and just found out that: in C# all of the fields and methods in a class are default private. Meaning that this:

```<code>class MyClass
{

string myString

}
</code>```

is the same as:

```<code>class MyClass
{

private string myString

}
</code>```

So because they are the same should I ever use the keyword private on fields and methods? Many online code samples use the keyword private in their code, why is that?


答:
C# is not the only programming language for .NET; other languages can and do have different default accessibility in various contexts.  Specifying private will make it clear to anyone reading the code that such accessibility is intended, whereas omitting the spec leaves open the question of whether the member might have been e.g. intended to be usable within the assembly [as would be the default in VB.NET].  Being explicit may be especially useful if one uses multiple languages with different rules.

With regard to whether private or protected should be favored in the absence of a particularly compelling argument in favor of the other, the decision should be based upon whether it is more likely that exposing a member may make it possible for a derived class to do something useful that would otherwise not be possible, or that it would prevent future versions of a class from modifying their internal data structures in a fashion that would be more efficient.  One may see examples of both situations in List<T>.

In some cases, if one has a list of aggregates (e.g. Point structures) it may be useful to update items in-place.  If List<T> exposed its backing store to derived classes, one could easily define an EditableList<T> with a method:

```<code>delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);

void ActOnItem<TParam>(int index, ref TParam param, ActByRef<TParam> proc)
{
  .. test index, then...
  proc(ref _arr[index], ref proc);
}
</code>```

which would could then be invoked using something like:

```<code>int adjustmentAmount = ...;
myList.ActOnItem(index, ref adjustmentAmount,
  (ref Point pt, ref int dx) => pt.X += dx );
</code>```

Such a method could allow efficient updates even with relatively large structure types [since no copying would be required].  The fact that List<T> does not expose its internals makes it impossible to derive a class which could implement such an operator efficiently.

On the flip side, although so far as I know Microsoft has not yet exploited this ability, having the backing store be private would make it possible for a future version of List<T> to split the backing store into pieces that were smaller than 85K when using most data types, or smaller than 1000 items when using double.  Such a split would not be possible if List<T> had exposed the backing store to derived classes.

Body:
C# is not the only programming language for .NET; other languages can and do have different default accessibility in various contexts.  Specifying private will make it clear to anyone reading the code that such accessibility is intended, whereas omitting the spec leaves open the question of whether the member might have been e.g. intended to be usable within the assembly [as would be the default in VB.NET].  Being explicit may be especially useful if one uses multiple languages with different rules.

With regard to whether private or protected should be favored in the absence of a particularly compelling argument in favor of the other, the decision should be based upon whether it is more likely that exposing a member may make it possible for a derived class to do something useful that would otherwise not be possible, or that it would prevent future versions of a class from modifying their internal data structures in a fashion that would be more efficient.  One may see examples of both situations in List<T>.

In some cases, if one has a list of aggregates (e.g. Point structures) it may be useful to update items in-place.  If List<T> exposed its backing store to derived classes, one could easily define an EditableList<T> with a method:

delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);

void ActOnItem<TParam>(int index, ref TParam param, ActByRef<TParam> proc)
{
  .. test index, then...
  proc(ref _arr[index], ref proc);
}

which would could then be invoked using something like:

int adjustmentAmount = ...;
myList.ActOnItem(index, ref adjustmentAmount,
  (ref Point pt, ref int dx) => pt.X += dx );

Such a method could allow efficient updates even with relatively large structure types [since no copying would be required].  The fact that List<T> does not expose its internals makes it impossible to derive a class which could implement such an operator efficiently.

On the flip side, although so far as I know Microsoft has not yet exploited this ability, having the backing store be private would make it possible for a future version of List<T> to split the backing store into pieces that were smaller than 85K when using most data types, or smaller than 1000 items when using double.  Such a split would not be possible if List<T> had exposed the backing store to derived classes.


问:
In UML is it correct to have an association class with a composition or aggregation relationship?
An example of an association class is given here:

http://pic.dhe.ibm.com/infocenter/rsarthlp/v9/index.jsp?topic=%2Fcom.ibm.xtools.modeler.doc%2Ftopics%2Fcassnclss.html

Composition and Aggregation are also types of Associations, just with more defined semantics to what the association consists of.

Can association classes also be part of a relationship by Composition or Aggregation? That is, in the case where there is a many-to-many relationship between two entities, with some additional attributes on the relationship. Or would it be more correct to model that as two separate one-to-many relationships onto a middle entity that hold the additional attributes?

答:
The UML concept of an "association class" is questionable (in terms of its semantics and usability) and I'd recommend not using it, but always explicitly express the class representing the association, connecting it to the participating object classes with many-to-one associations.

The questionable usability of the "association class" concept is illustrated by the flawed IBM example Student-Enrollment-Course referenced in your question. In this example, contrary to what is stated, Enrollment cannot be an "association class" if Course represents the general concept of a course offering (without semester information), because an "association class" admits of only one link between the same participant objects (a student and a course), while the domain semantics requires that a student can repeatedly take a course, implying more than one enrollment link between the same student and the same course.


问:
How to replace inheritance with composition in this case?
I've recently read several articles about the advantages of the composition over inheritance. Their authors said that you can always replace inheritance with composition (to be precise, they say they don't know such situations where it can't be done). However, I can't think how to do this in the following case:

```<code>abstract class Reader
{
    public Int32 ReadSum()
    {
        return this.ReadValue() + this.ReadValue();
    }

    public Int32 ReadSub()
    {
        return this.ReadValue() - this.ReadValue();
    }

    public Int32 ReadMul()
    {
        return this.ReadValue() * this.ReadValue();
    }

    public Int32 ReadDiv()
    {
        return this.ReadValue() / this.ReadValue();
    }

    public abstract Int32 ReadValue();
}

class RandomSource: Reader
{
    public Int32 ReadValue()
    {
        return Math.RandomInt32();
    }
}

class UserSource: Reader
{
    public Int32 ReadValue()
    {
        return Console.ReadInt32();
    }
}
</code>```

Is this at all possible?

答:
This example is a bit contrived but here's one way.

You seem to have things going on here - operations and reading. The reading should be done by Reader and the operations can be performed by a different class.

```<code>class ReadOperations {

     private Reader reader;

     public Int32 ReadSum()
     {
       return reader.ReadValue() + reader.ReadValue();
     }

     public Int32 ReadSub()
     {
        return reader.ReadValue() - reader.ReadValue();
     }

     public Int32 ReadMul()
     {
       return reader.ReadValue() * reader.ReadValue();
     }

     public Int32 ReadDiv()
     {
        return reader.ReadValue() / reader.ReadValue();
     }

}

interface Reader {

  public Int32 ReadValue();
}

class RandomSource: Reader
{
    public Int32 ReadValue()
    {
        return Math.RandomInt32();
    }
}

class UserSource: Reader
{
    public Int32 ReadValue()
    {
        return Console.ReadInt32();
    }
}
</code>```

Depending on what you want there are other ways to do this.

You should have to find a way to inject the reader - probably with a constructor.

Disclaimer - for practical purposes you don't "need" to use composition, but doing so is extensible and you should use it whenever you think your program can evolve in a certain direction.

In this case, if you think your operations will evolve independently from the way you "read".

Body:
This example is a bit contrived but here's one way.

You seem to have things going on here - operations and reading. The reading should be done by Reader and the operations can be performed by a different class.

class ReadOperations {

     private Reader reader;

     public Int32 ReadSum()
     {
       return reader.ReadValue() + reader.ReadValue();
     }

     public Int32 ReadSub()
     {
        return reader.ReadValue() - reader.ReadValue();
     }

     public Int32 ReadMul()
     {
       return reader.ReadValue() * reader.ReadValue();
     }

     public Int32 ReadDiv()
     {
        return reader.ReadValue() / reader.ReadValue();
     }

}

interface Reader {

  public Int32 ReadValue();
}

class RandomSource: Reader
{
    public Int32 ReadValue()
    {
        return Math.RandomInt32();
    }
}

class UserSource: Reader
{
    public Int32 ReadValue()
    {
        return Console.ReadInt32();
    }
}

Depending on what you want there are other ways to do this.

You should have to find a way to inject the reader - probably with a constructor.

Disclaimer - for practical purposes you don't "need" to use composition, but doing so is extensible and you should use it whenever you think your program can evolve in a certain direction.

In this case, if you think your operations will evolve independently from the way you "read".


问:
Web design standards
While designing web pages using php, are there standards that should be followed? For example suppose there are two pages. First page looks like this:

```<code><body>
<div>
<?php include 'page2.php';?>
</code>```

page2.php file looks like this:

```<code><?php print 'some text';?>
</div>
</body>
</code>```

Is such designing a standard practice? Does it affect search engine results?

答: You generate legal HTML that way, but I wouldn't recommend it. Putting a closing tag in a different file than the opening tag makes for poor readability and error prone design. As opposed to many other dubious designs I don't see any upside of this either, you will not be able to implement some smart trick because of this practice.</p>

OwnerDisplayName: Sanket Raut

Title: Web design standards


答:
Sure, for example you can pass the reading behaviours into the Reader class from outside:

```<code>class Reader
{
    private Func<Int32> read;

    public Reader(Func<Int32> read)
    {
        this.read = read;
    }

    public Int32 ReadSum()
    {
        return read() + read();
    }

    …

}
</code>```

Then you say something like new Reader(() => Math.RandomInt32()) to construct the equivalent of a RandomSource, or new Reader(() => Console.ReadInt32()) for a UserSource.

In general, replacing inheritance with composition leads to fewer nominal types such as UserSource, because their behaviour emerges from the composition of simpler components. You can of course make “constructor functions” like NewUserSource() for the sake of convenience.

(I’m not up on my C#, so bear with me if I’ve gotten some minor language details wrong here.)

Title: How to replace inheritance with composition in this case?

Body:
I've recently read several articles about the advantages of the composition over inheritance. Their authors said that you can always replace inheritance with composition (to be precise, they say they don't know such situations where it can't be done). However, I can't think how to do this in the following case:

```<code>abstract class Reader
{
    public Int32 ReadSum()
    {
        return this.ReadValue() + this.ReadValue();
    }

    public Int32 ReadSub()
    {
        return this.ReadValue() - this.ReadValue();
    }

    public Int32 ReadMul()
    {
        return this.ReadValue() * this.ReadValue();
    }

    public Int32 ReadDiv()
    {
        return this.ReadValue() / this.ReadValue();
    }

    public abstract Int32 ReadValue();
}

class RandomSource: Reader
{
    public Int32 ReadValue()
    {
        return Math.RandomInt32();
    }
}

class UserSource: Reader
{
    public Int32 ReadValue()
    {
        return Console.ReadInt32();
    }
}
</code>```

Is this at all possible?

Body:
Sure, for example you can pass the reading behaviours into the Reader class from outside:

class Reader
{
    private Func<Int32> read;

    public Reader(Func<Int32> read)
    {
        this.read = read;
    }

    public Int32 ReadSum()
    {
        return read() + read();
    }

    …

}

Then you say something like new Reader(() => Math.RandomInt32()) to construct the equivalent of a RandomSource, or new Reader(() => Console.ReadInt32()) for a UserSource.

In general, replacing inheritance with composition leads to fewer nominal types such as UserSource, because their behaviour emerges from the composition of simpler components. You can of course make “constructor functions” like NewUserSource() for the sake of convenience.

(I’m not up on my C#, so bear with me if I’ve gotten some minor language details wrong here.)


问:
A possible loophole on the 3-Clause BSD license
In a license.txt file, this:

```<code> Part of this program uses the following clause

 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in
 the documentation and/or other materials provided with the distribution.
</code>```

is definitely different from this:

```<code> 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in
 the documentation and/or other materials provided with the distribution.
</code>```

When applying the second clause of a 3-clause BSD license without "Part of this program uses the following clause", does bundling the library mean that my created application has to be governed by the 3-clause BSD license also?  E.g. my program should have no warranties, etc?

答:
That clause in the BSD license does not extend the license to the rest of your application.

What that clause means is that, at least, you must have a section in the documentation of your application along the lines of

Parts of this application are governed by the BSD license:

  < text of the BSD license goes here >

It is usually appreciated if you also identify which parts are under the other license, but that is not a requirement.


问:
Best practices for implementing MVVM and MVC in delphi Pascal
I'm a Delphi pascal programmer, I use the latest Embarcadero delphi XE, and I would like to take advantage of design patterns such as Model view controller and model view view-model.

However, there doesn't seem to be much on the web about the best practices for doing this in pascal. Most of the examples that I can find are in C# and some of the language features are not present in pascal, which means I may have to find ways to implement those features.

I'm trying to adapt code from this article here

I'll list the issues that I'm facing

Nullable types

Pascal does not have nullable types as C# does so I have created my own.

```<code>TNullable<T> = record
    strict private
      fHasValue : boolean;
      fValue : T;
      function GetValue:T;
      procedure SetValue(newValue : T);
    public
      property HasValue : boolean read fHasValue;
      property Value : T read GetValue write SetValue;
      procedure SetToNull;
    end;
</code>```

in the implementation section

```<code>function TNullable<T>.GetValue:T;
begin
    if fHasValue then
    begin
        Result := fValue;
    end
    else raise Exception.Create('Value Not Set');
end;

procedure TNullable<T>.SetValue(newValue : T);
begin
    fValue := newValue;
    fHasValue := true;
end;

procedure TNullable<T>.SetToNull;
begin
    fHasValue := false;
end;
</code>```

Get/Set for properties

Now that I have a nullable type I can create nullable properties
However it comes with some code smells

for example if i create

```<code>    TFoo = class
      private
        function GetBar:TNullable<Integer>;
        procedure SetBar(x:TNullable<Integer>);
      public
        property Bar : TNullable<Integer> read GetBar write SetBar;
</code>```

in the implementation section

```<code>function TFoo.GetBar:TNullable<Integer>;
begin
    if **valueExists** then
    begin
        Result.Value := **the value**
    end else
    begin
        Result.SetToNull;
    end;
end;

procedure TFoo.SetBar(x:TNullable<Integer>);
begin
    if X.hasValue then
    begin
        //Store/show value here
    end else
    begin
        //handle null assignment here
    end;
end;
</code>```

This is fine but when it comes to use these properties I can't just use

myFoo.Bar.Value := 1;

I have to use

```<code>var
    myBar : TNullable<Integer>;
begin
    myBar.Value := 1;
    myFoo.Bar := myBar;
end;
</code>```

Which is a bit messier. I suppose there may be nothing I can do about this.

Circular References

I like to separate classes into different units.

ie:

keeping the user interface separate from the control logic and the model and data logic layer.

I can have a situation where 2 classes can reference each other. While this is a situation that for the most part I would like to avoid, there are occasions where this is needed.

for example

```<code>unit u_A;

interface

uses
  u_B
  ;

type
  TA = class
    public
       Foo : TB;
  end;

implementation

end;
</code>```

and another unit

```<code>unit u_B;

interface

uses
  u_A
  ;

type
  TB = class
    public
       Foo : TA;
  end;

implementation

end;
</code>```

This code is broken because the two classes include each other and this can not be done in pascal. This is not such a problem in C#. Solutions that I can think of: 1. include both classes in the same unit, although this is a problem if I do not think this suits the design. 2. Create another parent interface for B and inherit B from that, then this gets around it. Although this is messy for such a simple task.

Static classes

There aren't any static classes in Delphi, these are useful for control classes.

Best Container classes to use in Delphi

I'm currently using TList and TObjectList in Generics.Collections
They were introduced in Delphi XE I hope these are the best to use since delphi 7 didn't seem to have any good options.

I'm still thinking about event handlers and any issues that may arise there. Perhaps there are some other issues that I have not thought of yet.

Thanks for any advice.

答:
You should look into Spring4D as it already contains nullable types (similar implementation as yours with a little extra operator overloading) and way more powerful collection types than those in the RTL. They are also interfaced based which is very handy because you don't have to worry about lifetime management especially when passing them around.

For cross referencing problems I am suggesting coding against interfaces and use these as reference in another implementation rather than 2 implementations knowing each other.

As for the MVVM part you might look into DSharp which has a first version of a Caliburn Micro port for Delphi. It is very early stage and hardly documented but you might get some ideas how to achieve MVVM in Delphi using loosely coupled GUI and business logic connected with data bindings. The Blaise Pascal magazine had two articles about it if you are more interested.

P.S. I guess you mean you are using XE6 as that is the latest version.


问:
Why is there no WSDL type support for Web Api?
So I am just getting started with .Net WebApi and one thing that I am noticing straight away is that there is no Contract defining how the API looks and should be consumed (Request/Responses from each Action), this is usually in the form of a WSDL for WCF/Soap.

It seems to me like this is something that would be very valuable and make life a lot easier for consumers of your API.

Is there a reason there isn't one? Is there a programming paradigm or principle that I am unaware of? Is there a way I could create one?

答:
In a nutshell, because SOAP was designed to be self-descriptive: A SOAP endpoint usually includes a wsdl that describes what operations it provides, and how the data looks (by means of embedded XSD's) that each operation takes and/or returns.

Because of this self-descriptiveness, it is possible for an application such as Visual Studio to generate a webservice proxy for it.

In addition, there are several extensions to SOAP (the WS-* specifications) that allow encryption or transactional behaviour to be used with SOAP. The idea is that you can use SOAP as your one-stop shop to create enterprise-grade webservices.

On the other hand...

WebAPI is designed to provide REST services. The communication format for REST is usually JSON or plain xml - although it really doesn't matter, it could even be plain text. REST services follow a completely different philosophy: they are meant to be lightweight so that they can easily be consumed by client-side scripts as part of an AJAX solution, or by mobile devices.

As such, there is a need to keep the level of ceremony to a minimum, including self-descriptiveness. Also, even if you wanted to, most communication formats used in REST services (such as JSON) don't have a formal way of describing their contents anyway.

Summarizing, you could say that SOAP webservices are usually used to integrate (possibly disparate) solutions, whereas REST services are better suited to provide communication between parts of the same solution.


问:
java best practice to look for project essential files?
Usually when you do a new java project, there are several essential file such log4j properties file, other properties file and log file and you need to tell java where they are and where do you want to save the log file.

I don't want to hardcode the absolute path to these file because I am putting the projects in different machines at different development stages. For example, I using Eclipse/PC in dev stage, Ant/Unix in UAT and Production machine.

Here is my usual setup:

Project:
--src
--build
--conf
--log
--output

In my understanding, src and build directory are included in the classpath and could be read right away by this.getClass().getClassLoader().getResource(".").getPath() . However, there is not a logical method to locate the Project directory programmatically.

If I could locate the Project directory programmatically, I could tell the program that the files are at ${Project}/conf and save the log file in ${Project}/log.

Should I just use a shell script to define these variable before running the program?

答:
I have done something similar in the project I am currently building. I am having to access properties files that I have stored within the build, as well as outside the project. Which means that the files will be located outside of the resulting jar. So hopefully my method is helpful to you.

To access the internal file which is located inside the jar I use

```<code>Classname.class.getClassLoader().getResourceAsStream(fileName)
</code>```

And the external files I use

```<code>new FileInputStream(fileName);
</code>```

fileName is declared with the extension as well as any subfolders before it
eg. "thisfolder/thisfile.me"

Body:
I have done something similar in the project I am currently building. I am having to access properties files that I have stored within the build, as well as outside the project. Which means that the files will be located outside of the resulting jar. So hopefully my method is helpful to you.

To access the internal file which is located inside the jar I use

Classname.class.getClassLoader().getResourceAsStream(fileName)

And the external files I use

new FileInputStream(fileName);

fileName is declared with the extension as well as any subfolders before it
eg. "thisfolder/thisfile.me"


答:
SOAP, REST AND PEOPLE'S CREATIVITY

SOAP needs a description document like WSDL because each resource can be consumed with different messages, there are no definition on the protocol about constraints to the possible names/messages that you can manipulate a resource.

For example, in SOAP your web service that allow clients manipulate an user can expose the operation that create an user in many different messages, like:

```<code>addUser
createUser
insertUser
</code>```

Of course, these are just few sample messages, because I've see a lot of funny web services method names. There are really creative people out there.

In other hand, if you are exposing your underlying system using web api that really respect the REST principles, the client just need to know that you have a resource named Users, because there is 99% of chance that you can create an user in this way

```<code>POST /Users
</code>```

And this occurs for each operation you want to expose using SOAP or a web api REST.

Despite being SOAP a protocol, which restricts what you can or can not do, and be REST a style architecture, which leaves many open points of how to do things. There are efforts to define conventions of how to expose and consume REST web apis.

DESCRIBING A WEB API REST

In the field of how to describe a web api REST I can cite Swagger. It is not a attempt to create a WSDL like to web api REST, but it is a good attempt to create an open standard for describing web apis REST.

Swagger is a specification and complete framework implementation for
  describing, producing, consuming, and visualizing RESTful web
  services.

I use Swagger a lot and really love it, mainly because Swagger UI that allow you generate a nice live console and documentation for your web api.

There are many implementations of Swagger for most of languages: C#, Java, Python, Ruby, etc.

If you are using ASP .NET Web API, there a some projects to auto generate the Swagger specification, like Swagger.NET

GENERATING CLIENTS TO A WEB API REST

Because the constraints of REST, like the limited set of verbs (GET, POST, PUT, DELETE, etc) is not so difficuty to generate a client library to a web api REST.

Projects like WebApiProxy can easily generate clients do C# and Javascript.

CONVENTIONS FOR WEB API REST

To keep our lifes as developers easier is good define some conventions of how our web api REST will behave, the best effort I know in this field is the very good Apigee - Web Api Design ebook. The e-book is not an attempt to create a bible or a mantra about how to design your api, but rather a collection of conventions observed in large web REST apis, like Twitter, Facebook, Linkedin, Google, etc.

Title: Why is there no WSDL type support for Web Api?

Body:
So I am just getting started with .Net WebApi and one thing that I am noticing straight away is that there is no Contract defining how the API looks and should be consumed (Request/Responses from each Action), this is usually in the form of a WSDL for WCF/Soap.

It seems to me like this is something that would be very valuable and make life a lot easier for consumers of your API.

Is there a reason there isn't one? Is there a programming paradigm or principle that I am unaware of? Is there a way I could create one?

Body:
SOAP, REST AND PEOPLE'S CREATIVITY

SOAP needs a description document like WSDL because each resource can be consumed with different messages, there are no definition on the protocol about constraints to the possible names/messages that you can manipulate a resource.

For example, in SOAP your web service that allow clients manipulate an user can expose the operation that create an user in many different messages, like:

addUser
createUser
insertUser

Of course, these are just few sample messages, because I've see a lot of funny web services method names. There are really creative people out there.

In other hand, if you are exposing your underlying system using web api that really respect the REST principles, the client just need to know that you have a resource named Users, because there is 99% of chance that you can create an user in this way

POST /Users

And this occurs for each operation you want to expose using SOAP or a web api REST.

Despite being SOAP a protocol, which restricts what you can or can not do, and be REST a style architecture, which leaves many open points of how to do things. There are efforts to define conventions of how to expose and consume REST web apis.

DESCRIBING A WEB API REST

In the field of how to describe a web api REST I can cite Swagger. It is not a attempt to create a WSDL like to web api REST, but it is a good attempt to create an open standard for describing web apis REST.

Swagger is a specification and complete framework implementation for
  describing, producing, consuming, and visualizing RESTful web
  services.

I use Swagger a lot and really love it, mainly because Swagger UI that allow you generate a nice live console and documentation for your web api.

There are many implementations of Swagger for most of languages: C#, Java, Python, Ruby, etc.

If you are using ASP .NET Web API, there a some projects to auto generate the Swagger specification, like Swagger.NET

GENERATING CLIENTS TO A WEB API REST

Because the constraints of REST, like the limited set of verbs (GET, POST, PUT, DELETE, etc) is not so difficuty to generate a client library to a web api REST.

Projects like WebApiProxy can easily generate clients do C# and Javascript.

CONVENTIONS FOR WEB API REST

To keep our lifes as developers easier is good define some conventions of how our web api REST will behave, the best effort I know in this field is the very good Apigee - Web Api Design ebook. The e-book is not an attempt to create a bible or a mantra about how to design your api, but rather a collection of conventions observed in large web REST apis, like Twitter, Facebook, Linkedin, Google, etc.


问:
Reactive programming vs MVVM pattern for managing GUI updates
Reactive programming and MVVM are two approaches that can address the problem of separating the domain layer from the UI.

MVVM does this by defining a viewmodel, which is a data structure mapped to UI components. The UI display the data, and maybe update it when user occurs.

a reactive framework defines a graph of observables which notify the UI that some piece of data has changed

Reactive frameworks are gaining mind share, both in mainstream platforms (with Rx in .net & java, react.js) and more experimental places (FRP in haskell).

I have mainly used MVVM with angular, and I find the simplicity to expressiveness ratio quite satisfying, although I have only worked on small/medium projects with it.

What does a reactive framework buys the developer that mvvm don't?

Is there really a difference? For example, knockout.js is advertised as a mvvm framework, but has a reactive feeling in its interface:

```<code>this.firstName = ko.observable("John");
this.lastName = ko.observable("Smith");

this.fullName = ko.computed(function() {
    return this.firstName() + " " + this.lastName();
}, this);
</code>```

答:
Those are different non-competing concepts and they can easily work together to produce a great result.

In layman terms:

MVVM is useful to get away from the codebehind (GUI/model coupling) clutter.
Reactive approach is useful to reduce the event/callback clutter.

I would recommend learning a bit about XAML/WPF since Microsoft is the original inventor of the MVVM. Microsoft also produced a very good implementation of Reactive approach: Reactive Extensions.

Here is a decent attempt to combine them:

http://www.reactiveui.net
https://github.com/reactiveui/ReactiveUI

Related SO question:

https://stackoverflow.com/questions/1763411/reactive-extensions-rx-mvvm


问:
Multiple classes with the same name, but different namespaces?
I've run into some code (C# if it matters) that has classes which have the same name, but differ in their namespaces. They all tend to represent the same logical thing, but often are different "views" of the same object. The different namespaces are at times part of the same solution, and even the same dll.

I have my thoughts, but couldn't find anything definitive about this practice to be considered a clever use of the tools available or a pattern to avoid.

This question on smurf naming touches on this, but from the other direction. Disambiguating the names would likely require an arbitrary and pervasive prefix, which that question wanted to eliminate.

What are the guidelines around this practice?

答:
The Scala Collection Framework is a good example of this. There are mutable and immutable collections as well as serial and parallel (and in the future maybe distributed as well) collections. So, there are, for example, four Map traits:

```<code>scala.collection.Map
scala.collection.immutable.Map
scala.collection.mutable.Map
scala.collection.concurrent.Map
</code>```

plus three ParMaps:

```<code>scala.collecion.parallel.ParMap
scala.collecion.parallel.immutable.ParMap
scala.collecion.parallel.mutable.ParMap
</code>```

Even more interesting:

```<code>scala.collection.immutable.Map            extends scala.collection.Map
scala.collection.mutable.Map              extends scala.collection.Map
scala.collection.concurrent.Map           extends scala.collection.mutable.Map

scala.collecion.parallel.ParMap           extends scala.collection.Map
scala.collecion.parallel.immutable.ParMap extends scala.collecion.parallel.ParMap
scala.collecion.parallel.mutable.ParMap   extends scala.collecion.parallel.ParMap
</code>```

So, ParMap extends ParMap extends Map and Map extends Map extends Map.

But, let's face it: what else would you call them? This makes perfect sense. That's what namespaces are for!

Body:
The Scala Collection Framework is a good example of this. There are mutable and immutable collections as well as serial and parallel (and in the future maybe distributed as well) collections. So, there are, for example, four Map traits:

scala.collection.Map
scala.collection.immutable.Map
scala.collection.mutable.Map
scala.collection.concurrent.Map

plus three ParMaps:

scala.collecion.parallel.ParMap
scala.collecion.parallel.immutable.ParMap
scala.collecion.parallel.mutable.ParMap

Even more interesting:

scala.collection.immutable.Map            extends scala.collection.Map
scala.collection.mutable.Map              extends scala.collection.Map
scala.collection.concurrent.Map           extends scala.collection.mutable.Map

scala.collecion.parallel.ParMap           extends scala.collection.Map
scala.collecion.parallel.immutable.ParMap extends scala.collecion.parallel.ParMap
scala.collecion.parallel.mutable.ParMap   extends scala.collecion.parallel.ParMap

So, ParMap extends ParMap extends Map and Map extends Map extends Map.

But, let's face it: what else would you call them? This makes perfect sense. That's what namespaces are for!


问:
WCF vs Web API, Deeper details?
Before I continue, I just want to mention I have heavily researched and searched on this topic, but I need the opinion of people who have worked/and or have practical knowledge with regards to this topic.

We are currently looking at developing an API so that clients can utilize this. We are definitely set on REST as opposed to SOAP, but I am still a little unclear about what exactly the difference is, if you go down to microscopic detail.

Having a look at msdn (Choosing which technology to use), the link below:

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

The differences are clear. However, the first point states for WCF:

Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them.

For ASP.NET Web Api:

HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.

So, both support HTTP, but WCF supports more protocols in addition. What makes ASP.NET Web API more suitable for, I quote: "More suitable for access from various browsers, mobile devices etc enabling wide reach." if both support HTTP?

We have until now, relied heavily on PC use. What I am getting to, and finally my question is:

We plan on going mobile, and moving a lot more to multiple devices, browsers etc. But I just would not like to go on a service on the basis of a bit of text saying "Web API" is more suitable? IS it more efficient, less resource intensive etc.? With regards to future proofing? Would we be better of with WEB API and why? Just lastly, we have existing SOAP services, everything we have is built in SOAP.

Please do not hesitate to go into detail, I am not an experienced dev, just trying to add a contribution to this project.

Just a last couple of requirements:

1) We plan on utilizing JSON.
2) We are limited to .NET 3.5/4.
3) Must be REST.

答:
Its all hype for the different products written by different product teams with incentive to get their baby adopted. Ignore them all and evaluate what you need, not what they need you to want.

What I do know if that ASP.NET projects require a heap of infrastructure (eg IIS, and associated configuration), whereas WCF can be built as stand-alone services that just run with minimal configuration (typically registering the root URL with http.sys). This is the biggest win for me - recently we had some older ASP.NET projects that we had to integrate with, and what could have been an easy task with some WCF services was a huge PiTA as we had to go through a mass of setup instructions (that were not necessarily up to date, of course) to get something working, not to mention the installation of system services to do this.

So you need to consider the future maintenance involved. If WebAPI requires a heap of setup, then I'd avoid it.

There are alternatives, WWS is much more efficient as WCF and supports the same protocols (not that it matters if you're only using HTTP). If you are just building a REST API then any web server, embedded or not, will do. (eg I added Mongoose to one of my services recently, so now it serves http to clients as well, seamlessly and really simple though using C++ not C#).

Title: WCF vs Web API, Deeper details?


问:
The problems with Avoiding Smurf Naming classes with namespaces
I pulled the term smurf naming from here (number 21). To save anyone not familiar the trouble, Smurf naming is the act of prefixing a bunch of related classes, variables, etc with a common prefix so you end up with "a SmurfAccountView passes a SmurfAccountDTO to the SmurfAccountController", etc.

The solution I've generally heard to this is to make a smurf namespace and drop the smurf prefixes. This has generally served me well, but I'm running into two problems.

I'm working with a library with a Configuration class. It could have been called WartmongerConfiguration but it's in the Wartmonger namespace, so it's just called Configuration. I likewise have a Configuration class which could be called SmurfConfiguration, but it is in the Smurf namespace so that would be redundant. There are places in my code where Smurf.Configuration appears alongside Wartmonger.Configuration and typing out fully qualified names is clunky and makes the code less readable. It would be nicer to deal with a SmurfConfiguration and (if it was my code and not a library) WartmongerConfiguration.

I have a class called Service in my Smurf namespace which could have been called SmurfService. Service is a facade on top of a complex Smurf library which runs Smurf jobs. SmurfService seems like a better name because Service without the Smurf prefix is so incredibly generic. I can accept that SmurfService was already a generic, useless name and taking away smurf merely made this more apparent. But it could have been named Runner, Launcher, etc and it would still "feel better" to me as SmurfLauncher because I don't know what a Launcher does, but I know what a SmurfLauncher does. You could argue that what a Smurf.Launcher does should be just as apparent as a Smurf.SmurfLauncher, but I could see `Smurf.Launcher being some kind of class related to setup rather than a class that launches smurfs.

If there is an open and shut way to deal with either of these that would be great. If not, what are some common practices to mitigate their annoyance?

答:
I've run up against this same point of confusion before and it's usually really a question of do we include the kind of thing it is as part of it's name.

You mention SmurfConfiguration and WartmongerConfiguration as potential kinds of configurations.  You indicate that you removed the adjective (its kind) to its namespace so that what you're left with is just the vanilla Configuration.  I would avoid doing that.

It's like deciding that strawberry ice cream is just ice cream in the strawberry namespace and likewise with chocolate, but what's happened is you've divorced the adjective that gives it its identity from the thing itself.  It's not ice cream in the strawberry category.  It's strawberry ice cream -- a kind of ice cream.

Let's imagine that in your app, you import the Strawberry.IceCream class and then start instantiating directly from IceCream.

```<code>var ic = new IceCream(); //actually I'm strawberry ice cream
</code>```

This may seem well and good, up until the moment you end up importing another IceCream class.  Now you're back to the original problem of having to somehow distinguish between them, which is problematic.  What you wanted all along was:

```<code>var sic = new StrawberryIceCream();
var cic = new ChocolateIceCream();
</code>```

Namespaces are better left to avoid potential conflicts between third parties who might incidentally represent the same concepts in their libraries.  When one developer creates a library or project, however, he should name each concept uniquely and use namespaces as folders for organization only.  Often the name of the folder will be found in the name of the concepts it organizes and that's okay.

Body:
I've run up against this same point of confusion before and it's usually really a question of do we include the kind of thing it is as part of it's name.

You mention SmurfConfiguration and WartmongerConfiguration as potential kinds of configurations.  You indicate that you removed the adjective (its kind) to its namespace so that what you're left with is just the vanilla Configuration.  I would avoid doing that.

It's like deciding that strawberry ice cream is just ice cream in the strawberry namespace and likewise with chocolate, but what's happened is you've divorced the adjective that gives it its identity from the thing itself.  It's not ice cream in the strawberry category.  It's strawberry ice cream -- a kind of ice cream.

Let's imagine that in your app, you import the Strawberry.IceCream class and then start instantiating directly from IceCream.

var ic = new IceCream(); //actually I'm strawberry ice cream

This may seem well and good, up until the moment you end up importing another IceCream class.  Now you're back to the original problem of having to somehow distinguish between them, which is problematic.  What you wanted all along was:

var sic = new StrawberryIceCream();
var cic = new ChocolateIceCream();

Namespaces are better left to avoid potential conflicts between third parties who might incidentally represent the same concepts in their libraries.  When one developer creates a library or project, however, he should name each concept uniquely and use namespaces as folders for organization only.  Often the name of the folder will be found in the name of the concepts it organizes and that's okay.


问:
How does requirements management work in the long term with Agile projects?
Requirements Management in the short term for Agile projects seems like a solved problem to me.

From the Scrum angle new requirements or changes to existing requirements are delivered through User Stories.  And User Stories grouped under an Epic or Feature facilitate the delivery of larger more complex requirements.

Of course, a User Story isn't technically a requirements document.  It is a manageable grouping of work which maps to what is often called a Vertical Slice of functionality.  And the scope of these stories can be defined unambiguously through the use of Acceptance Criteria (AC).

So, although User Stories aren't formal requirements, browsing through them can give you a pretty clear idea of their underlying requirements.  In the short term.

I say in the short term because, as a project progresses, the number of User Stories increases.  Thus, browsing through an ever increasing list of Stories to find a Requirement becomes less and less efficient over time.

This problem is compounded when you consider User Stories that expand on, supersede, or even negate previous Stories.

Now, imagine a 2 year gap between development iterations on a project (stable in production).  The original team is gone and so is all their knowledge.

If the original team knew this was going to happen (eg, it's the nature of the business), then what measures could they take to help subsequent teams?

Sure, the backlog will provide some information, but it's hardly in an easily browsable form.

So, what can be done to help subsequent teams understand the state of the project, including why and how it got there?

In my experience, the following things don't work:

Backlog grooming to delete or update previous User Stories so that the Backlog can be read as a requirements document.

Documentation Sprints where team members are tasked with documenting the current state of the system.

Documentation through Behaviour Tests.  This approach is the only one I have seen come close to working.  Unfortunately, Coded Behaviour tests are victims the Naming Problem.  Although the tests might properly document the system, getting a fluctuating team of developers to write their tests following the same Domain terminology, wording, and style is almost impossible.

So, to reiterate:

How does one manage Agile project Requirements in the long term?

答:
I am actually working in a kanban maintenace project of a big web shop where the original developpers are not available any more.

every userstory/requirement/bugfix has a ticketnumber and every sourcecode-change is linked to a ticketnumber in the sourcecontrol-comment-field.

sourcecontrol-checkin-s (svn) atomatically update the coressponding ticket so that in the ticket i have a link to all sourceconrtol-changesets.

If a modul/function is newly implemented there are ticketnumbers in the sourcecode, too.

In the ticket-system (redmine) the tickets are linked among each other as (is duplicate, is bug, is refinement of, ....)

so you can follow the tickets and see requirement changes over time.

Example: i have to chage something in the "orderConfirmation-Web-page". In the sourcecode of the page i see a comment: 'created for "#4711"'
so i can link my new ticket to the old ticket "4711" or one of its successors.


答:
Personally, I discard the user stories as a source of documentation on what the system can do. Unless active steps have been taken to create documentation (which we have done for some of our more traditional clients) the application base is really the best documentation there is.

Although, that's nothing new.

If you are using a more scaled version of Agile (like SAFe), you'll have other backlogs that are not the implementation backlog. It basically looks like this:

Portfolio Backlog (Strategic planning of epics and budgets)

Program/Release Backlog (Features and Epics)

Project/Team Backlog (Stories, Spikes, Bugs)

I would not recommend documenting at the Team Backlog level. It's too granular and rarely does anybody want to go to that level of detail. Not to mention that there may be stories within a Release that contradict previous stories in the Team backlog.

Instead, I would recommend working at your Release Backlog level to provide Release-level documentation. These stories rarely blow out once assigned to a particular release, and can be a stable and quick way to review what is being worked on within a given release.

Title: How does requirements management work in the long term with Agile projects?

Body:
Requirements Management in the short term for Agile projects seems like a solved problem to me.

From the Scrum angle new requirements or changes to existing requirements are delivered through User Stories.  And User Stories grouped under an Epic or Feature facilitate the delivery of larger more complex requirements.

Of course, a User Story isn't technically a requirements document.  It is a manageable grouping of work which maps to what is often called a Vertical Slice of functionality.  And the scope of these stories can be defined unambiguously through the use of Acceptance Criteria (AC).

So, although User Stories aren't formal requirements, browsing through them can give you a pretty clear idea of their underlying requirements.  In the short term.

I say in the short term because, as a project progresses, the number of User Stories increases.  Thus, browsing through an ever increasing list of Stories to find a Requirement becomes less and less efficient over time.

This problem is compounded when you consider User Stories that expand on, supersede, or even negate previous Stories.

Now, imagine a 2 year gap between development iterations on a project (stable in production).  The original team is gone and so is all their knowledge.

If the original team knew this was going to happen (eg, it's the nature of the business), then what measures could they take to help subsequent teams?

Sure, the backlog will provide some information, but it's hardly in an easily browsable form.

So, what can be done to help subsequent teams understand the state of the project, including why and how it got there?

In my experience, the following things don't work:

Backlog grooming to delete or update previous User Stories so that the Backlog can be read as a requirements document.

Documentation Sprints where team members are tasked with documenting the current state of the system.

Documentation through Behaviour Tests.  This approach is the only one I have seen come close to working.  Unfortunately, Coded Behaviour tests are victims the Naming Problem.  Although the tests might properly document the system, getting a fluctuating team of developers to write their tests following the same Domain terminology, wording, and style is almost impossible.

So, to reiterate:

How does one manage Agile project Requirements in the long term?


问:
boolean operations in C using bitfields
I am trying to implement boolean data type in C. Basically, I am working with sets.

The following code can be used to access each bit but I am unsure whether I can represent sets using this method.
Can somebody clarify this for me?

```<code>struct SET {
unsigned int b0     :1;     // bit 0 single bit
unsigned int b1     :1;     // bit 1 single bit
unsigned int b2     :1;
 unsigned int b3    :1;
 };
</code>```

I can define two structures s1 and s2.. and I will be able to access each bit of these structures (treated as boolean strings).

I will have to perform set operations like UNION, INTERSECTION and MEMBERSHIP. Is this even possible in C?

Note: I cannot use Java, only C.

答:
C doesn't have any built-in set operations, but if your sets can be represented by a bitset with fewer than 64 bits (32 in older implementations), then you can use bit-operations to simulate the set operations (using AND (&) for set intersection and OR (|) for set union).

Your structure is easy for testing membership (just see if the corresponding member is not 0), but not that easy for operations on multiple bits. That is easier on an unsigned number. To get the best of both worlds, use a union:

```<code>union SET {
  struct items {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
    unsigned int e: 1;
    unsigned int f: 1;
    unsigned int g: 1;
    unsigned int h: 1;
  };
  uint8_t bits; // As we only have 8 items for our set
};
</code>```

You do the bit operations on the bits member, and the membership tests/sets on the items.[abcdefgh] members.

Title: boolean operations in C using bitfields

Body:
C doesn't have any built-in set operations, but if your sets can be represented by a bitset with fewer than 64 bits (32 in older implementations), then you can use bit-operations to simulate the set operations (using AND (&) for set intersection and OR (|) for set union).

Your structure is easy for testing membership (just see if the corresponding member is not 0), but not that easy for operations on multiple bits. That is easier on an unsigned number. To get the best of both worlds, use a union:

union SET {
  struct items {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
    unsigned int e: 1;
    unsigned int f: 1;
    unsigned int g: 1;
    unsigned int h: 1;
  };
  uint8_t bits; // As we only have 8 items for our set
};

You do the bit operations on the bits member, and the membership tests/sets on the items.[abcdefgh] members.


答:
In memory these can be accessed as flags, so you can use standard flag operations,

```<code>struct SET {
 unsigned int b0     :1;     // bit 0 single bit
 unsigned int b1     :1;     // bit 1 single bit
 unsigned int b2     :1;
 unsigned int b3     :1;
};

struct SETFlag {
    union {
        SET set;
        unsigned int set_as_flag;
    };
};

 /* example use */
 SETFlag a, b, c;
 /* initialize */
 c.set_as_flag = a.set_as_flag | b.set_as_flag;  /* union */
 /* c.set, now you can use set */
</code>```

This assumes you have <= 32 members for a 4 byte int, you could ensure its value is correct,

```<code>_Static_assert(sizeof(((struct SETFlag *)0)->set) <=
               sizeof(((struct SETFlag *)0)->set_as_flag),
               "SETFlag.set_as_flag is too small!");
</code>```

However all this begs the question, why not just use flags.

Title: boolean operations in C using bitfields

Body:
I am trying to implement boolean data type in C. Basically, I am working with sets.

The following code can be used to access each bit but I am unsure whether I can represent sets using this method.
Can somebody clarify this for me?

```<code>struct SET {
unsigned int b0     :1;     // bit 0 single bit
unsigned int b1     :1;     // bit 1 single bit
unsigned int b2     :1;
 unsigned int b3    :1;
 };
</code>```

I can define two structures s1 and s2.. and I will be able to access each bit of these structures (treated as boolean strings).

I will have to perform set operations like UNION, INTERSECTION and MEMBERSHIP. Is this even possible in C?

Note: I cannot use Java, only C.

Body:
In memory these can be accessed as flags, so you can use standard flag operations,

struct SET {
 unsigned int b0     :1;     // bit 0 single bit
 unsigned int b1     :1;     // bit 1 single bit
 unsigned int b2     :1;
 unsigned int b3     :1;
};

struct SETFlag {
    union {
        SET set;
        unsigned int set_as_flag;
    };
};

 /* example use */
 SETFlag a, b, c;
 /* initialize */
 c.set_as_flag = a.set_as_flag | b.set_as_flag;  /* union */
 /* c.set, now you can use set */

This assumes you have <= 32 members for a 4 byte int, you could ensure its value is correct,

_Static_assert(sizeof(((struct SETFlag *)0)->set) <=
               sizeof(((struct SETFlag *)0)->set_as_flag),
               "SETFlag.set_as_flag is too small!");

However all this begs the question, why not just use flags.


问:
Are bloom filters actually faster than hashes, even taking in account cache?
Bloom filters look really great when you consider you can determine if an Int is in a set with 99% certainty in constant time. But so can hashes, with the only difference that, in a hash, most of the time you are accessing the memory only once. With bloom filters, you need to access them ~7 times per request in completely distant places, so you'd have several cache misses per request.

Am I missing something?

答:
You are missing how the two data structures deal with hash collisions. The bloom filters do not store the actual values, so the required space is the constant size of the designated array. Instead if you use a traditional hash, it tries to store all the values you give it, so it grows with time.

Consider a simplified hash function (for the sake of an example only!) f(x) = x % 2. Now you input the following integers: 2, 3, 4, 5, 6, 7.

Standard Hash: the given values will be hashed, and we end up with a lot of collisions due to f(2) = f(4) = f(6) = 0 and f(3) = f(5) = f(7) = 1. Nevertheless, the hash stores all of these values and it will be able to tell you that 8 is not stored in it. How does it do that? It keeps track of collisions and stores all values with the same hash-value, then when you query it, it additionally compares your query. So let's query the map for 8: f(8) = 0, so it'll look into a bucket where we have already inserted 2, 4, 6 and needs to make 3 comparisons in order to tell you that 8 was not part of the input.

Bloom filter: Normally, each input value is hashed against k different hash functions. Again, for simplicity, let's just assume we only use the single hash function f. We need an array of 2 values then and when we encounter the input 2 it means that due to f(2) = 0 we set the array value at position 0 to the value 1. The same happens for 4 and 6. Similarly, the inputs 3, 5, 7 each set the array position 1 to value 1. Now we query if 8 was part of the input: f(8) = 0 and the array at position 0 is 1, so the bloom filter will falsely claim that 8 was indeed part of the input.

To get a bit more realistic, let's consider that we add a second hash function g(x) = x % 10. With that, the input value 2 leads to two hash values f(2) = 0 and g(2) = 2 and the two corresponding array positions will be set to 1. Of course, the array now should be at least of size 10. But when we query for 8 we will check the array at position 8 due to g(8) = 8, and that position will still be 0. That's why additional hash functions decrease the false positives you'll get.

Comparison: The bloom filter uses k hash functions which means up to k random array positions being accessed. But that figure is exact. The hash instead is only guaranteeing you an amortized constant access time, but may de-generate depending on the nature of your hash function and input data. So it is typically faster, except for the de-generated cases.

However, once you have a hash collision the standard hash will have to check equality of the stored values against the query value. This equality check may be arbitrarily expensive and will never occur with a bloom filter.

In terms of space, the bloom filter is constant, as there is never any need to use more memory than the designated array. On the other hand, the hash grows dynamically and may get much larger due to having to keep track of collisioned values.

Trade-off: Now that you know what is cheap and what not and under which circumstances, you should be able to see the trade-off. Bloom filters are great if you want to very quickly detect that a value has been seen previously, but can live with false positives. On the other hand, you can choose the hash map if you want guaranteed correctness at the price of not being able to exactly judge your runtime, but can accept occassionally degenerated cases which may be much slower than the average.

Similarly, if you are on a limited memory environment you may want to prefer bloom filters for their memory usage guarantee.


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
IMHO, language features such as operator overloading give the programmer more power.  And, as we all know, with great power comes great responsibility.  Features that give you more power also give you more ways to shoot yourself in the foot, and, obviously, should be used judiciously.

For example, it makes perfect sense to overload the + or the * operator for class Matrix or class Complex.  Everyone will instantly know what it means.  On the other hand, to me the fact that + means concatenation of strings is not at all obvious, even though Java does this as a part of the language, and STL does for std::string using operator overloading.

Another good example of when operator overloading makes code more clear is smart pointers in C++.  You want the smart pointers to behave like regular pointers as much as possible, so it makes perfect sense to overload the unary * and -> operators.

In essence, operator overloading is nothing more than just another way to name a function.  And there is a rule for naming functions: the name must be descriptive, making it immediately obvious what the function does.  The same exact rule applies to operator overloading.


问:
Naming: StartDate or StartDateTime when working with DateTimes
I am using a lot of DateTimes in my application. Now I usually name it like StartDateTime, EndDateTime, etc, to imply there is also a time involved.

I am getting a bit tired of this (it is tiresome to read), and most of the time it is quite logical there is a time compartment to it anyway.

Now I'm thinking about ditching StartDateTime in favor of the shorter StartDate, despite that there is also a time part included.

Question

What is better: easier to read vs being more explicit about that there is a time included?

(ps: I guess this has a lot to do with C# not having separate objects for Date and DateTime, so that's where the need for Hungarian comes from)

答:
I would generally expect DateTime objects, so I would go with Start and End if they were datetimes and allow people who are in doubt to check the type definition, intellisense or documents.

It seems logical to prefer the more specific StartDate and EndDate for cases where you have only a date, which is more likely to be a special case.

As a general rule, I prefer not to include the type in my variable names unless it is going to behave in an unexpected way. Where possible I try to find ways to avoid variables that behave in unexpected ways.


问:
Windows Permissions for Developers?
I work at a Fortune 500 company as a Windows software developer in R&D. Corporate IT is currently gearing up for a company-wide Win7 deployment and as a part of it they are looking to completely lock down admin rights on all boxes (including our dev workstations).

I've been tasked to work with them to make the transition as smooth as possible. Lucky me.

I'd like to know if there are any published or other highly respected resources out there that I can use to:

figure out where to draw a line in the sand

back up my position.

Personally, my take is that we're R&D and our job is to do things that are 'out of the box'.  Thus we need admin rights.  However, having started my career as a Windows Admin, I'm aware of their goals and what they need to achieve. What I need to figure out and back up is a way to build the environment in a way that both IT and R&D can live with it and continue to perform their jobs productively.

Development VMs with local admin rights will definitely help a lot, but not in all cases since we interface with lots of custom hardware.

The CIO pushing these changes is definitely a 'pure IT' kind of guy with limited knowledge of the development process so I need some references that would be appropriate to share with someone like that.

I'm not looking to gather a lot of personal opinions (a lot of which have already been shared here), I really need whitepapers, magazine articles, scholarly works, etc to use to make a strong case to upper management.

答:
Consider giving the developers two accounts.

The first is a normal non-privileged user account, which is the one to use for all everyday work (including software development).  The other is a local admin account, which only has admin privileges on specific machines.  It should only be needed when actually installing stuff or tweaking machine settings.

Ensure that everyday services such as the internet proxy server, email and so on only recognise the normal account, so developers can't just use the local admin one all the time.  Whenever admin privileges are required, UAC will pop up and offer the developer a chance to enter their local admin log-in details to proceed.

OwnerDisplayName: Dan

Title: Windows Permissions for Developers?


问:
Why does Microsoft still ship VBA within Office products, instead of integrating .NET directly?
I know that it's possible to call .NET code from your VBA code, but why does VBA continue to exist? The only reason I can think about is legacy.

I just had to sort a Scripting.Dictionary and the amount of code needed was frightening.

The IDE looks like Visual Studio 2003. And there are many little details, that drive you insane (Like changing the line, and getting a warning because of some compilation error). Or, if you open more than one spreadsheet, it mixes into you "VBAProject" and this is really confusing.

The whole module/classmodule/form division is actually not that bad, but I end up everytime with directly writing logic in forms, or having one huge module that handles everything.

Why can't I press Alt+F11, and hack in C#?

答: I think there is a slight, but important, difference between legacy and popularity. And when you've done as many contracts as I have, you learn that VBA is insanely popular :) I can't tell you how many contracts I've done for "Excel jockeys" that don't know a thing about programming but can crush VBA like it's a matter of life or death.