答:
Going against the flow I would say it depends on the context.

The term "C/C++" is usually not appropriate when saying something like "this is a C/C++ program", but this has been explored to depth in other answers.

However, there might be contexts where C/C++ can be appropriate.

There are various libraries which usually have both a C and a C++ API. I guess it's not far from the truth if you call such a thing a C/C++ library. We humans like to compress information, so saying "opencv is a C/C++ library" is short, clear, and understandable, compare it to saying "opencv is a library, which is shipped with headers both for C and C++".

You can talk about language design and syntax. From the point of view of the language syntax, you might say that a language has C/C++ -like syntax.

You organize a coding contest, and you accept both solutions written in C and in C++

You are hiring a new programmer, and most of the tasks will be either C or C++, so the programmer is expected to know both languages. It's common in embedded development, where C is more suitable for some (usually very small) microcontrollers, and C++ for others. In this case you might say you are looking for a C/C++ programmer.

Title: Should I stop using the term C/C++?


问:
Which programming language is used to write a BIOS program?
As I understand, the BIOS code/bitstream that is held in the ROM should be generic (work alongside with multiple CPU types or ISAs). In addition, I saw mentioned on the web that it is possible to dump its code (and to "disassemble" it).

So, in which language, instruction set or machine code is it written? Doesn't it need any kind of processor to perform its operations? If so, I guess that it will use the external CPU, then how does it know the specific instruction set of the employed one?

Maybe it has an internal processor?

答:
While in theory one can write BIOS in any language, the modern reality is most BIOS is written using Assembly, C, or a combination of the two.

BIOS must be written in a language that can compile to machine code, that is understood by the physical hardware-machine. This eliminates the directly or intermediate-ly interpreted languages (Perl, Python, PHP, Ruby, Java, C#, JavaScript, etc) as being appropriate for writing BIOS. (Though, in theory, one could implement one of these languages to either compile directly to static machine code or one could somehow embed the interpreter in BIOS. There is, for-example, the abandonware GCJ project for Java.)

Most OEMs implement a BIOS by extending proprietary, generic BIOS implementations by companies like American Megatrends and Phoenix Techologies. (You've probably seen one of those companies displayed on the first boot screen of a computer before.) The source code for these implementations is not publicly available, but some of it has been leaked. I do not want to link to this directly to the C and assembly source code, but there are places on the Internet where this source code is discussed for those who care to peek.

Some hardware manufacturers, like those targeting the high-performance and gaming markets, saturate their BIOS implementations with customization features, statistics, and attractive user interfaces designed for their exact implementations. Many of these features go beyond what is offered in the generic products produced by American Megatrends and others. Unfortunately, these companies often see the release of their source code as a security risk, so little is known about these high-end implementations because little is shared about them. One could of course find ways to access and de-compile such BIOS implementations but doing so may be difficult and possibly illegal.

Going back to the original question, because of the need to produce native machine code, a BIOS would have to be implemented in a programming language supported by a native machine code compiler. While there are many such languages and while I'm sure over the last few decades, several languages have been used in experimentation, every open BIOS implementation I have been able to find specifically relies on a combination of C and/or assembly. The open-sourced BIOS implementations I looked at to form this conclusion include OpenBIOS, tinyBIOS, coreboot, Intel BIOS, and Libreboot. I also looked at some very old BIOS implementations that are not relevant today but also followed the C and/or assembly rule.

I think it's also relevant to look at other software built to interact directly with hardware. We know, for example, that the Linux Kernel, the OS X kernel, and the Windows kernel are largely C with some assembly and some higher level languages for specific tasks. We also know that hardware drivers on Linux and hardware drivers on Windows are written largely in C.

Getting back to BIOS, I think it's also important to consider the economics of the programming language chosen. BIOS is generally written as a necessity to complement hardware sales. Modern BIOS systems are known to be largely written in C and/or assembly. A move to some other tool would add significant costs to what are generally considered to be commodity products which could very adversely affect sales. Without getting into Economics 101, I can assure you that it's probably not worth it to an OEM to deviate from tried-and-true tools that have been proven over decades.

Of course there are and will be hobbyist projects to write BIOS as well. These too, thus far, seem to be choosing C and/or assembly. Perhaps one day other technologies will be used. But today, the choice of is well-defined.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
What exactly is model driven software engineering (MDSE)?
I came accross the accronym MDSE today on infoq, and the information I could find what quite unclear and the description was full of buzzwords :

MDSE is about enabling software engineers to work at a level of abstraction where requirements, architecture and design information is maximally ordered (in terms of information "entropy") and preserved. (Call this the "design work product"). Further, MDSE should provide engineers with the means to verify and validate their designs primarily terms of their "design work product"

And apparently, everyone is doing it: (from the article again)

We’re at the dawning of the age of MDSE. In the next 5 – 10 years we will see a significant shift towards MDSE, to the extent that I believe that by the end of this period perhaps 60 – 80% of software will be designed using model based techniques.

I would like to have a concrete, buzzword-free description of what MDSE is. Is it drawing UML boxes and generating code with it, like they did in the 90s with Rational Rose?

(while were at it, if anyone has an example of software generated using those techniques, I would really like to see a concrete example).

答:
IMHO "model driven" is a big  exaggeration, especially when used in conjunction with buzzwords like "design" or "software engineering" (instead of "development"). It was probably invented by some people having the misconception "software design" is done by drawing some mostly graphical models with UML, like an architect is drawing a blueprint for a house, and "coding" is just like laying the bricks for the house, following the blueprint. (I hope I do not have to explain here why this is wrong, if you have a different opinion, please read "Code as Design" by Jack Reeves  first before downvoting me.)

This is a great mental model for those people calling themselves "architects", "business analysts", "designers", "software engineers", which have studied five years of computer science, but only half a year of real programming experience (at maximum), and now looking for a job in the software industry which includes "designing software" without coding. I guess this is the real reason why this "model driven" buzzwords are so popular.

Don't get me wrong, I am big fan of models and code generators for reducing the need to write boilerplate code manually. In some restricted areas like, for example, databases, (data) models can be indeed a good instrument for communicating with domain people. Sketching data flow between components by models is IMHO one of the most important techniques for bringing structure into a software system (unfortunately, the UML people forgot refused to include data flow diagrams in their notation; instead, they added a bunch of redundant, unnecessary stuff which nobody uses in practice).

But I would call this "model supported software development", not "model driven software engineering", which makes hopefully clear that modeling just supports the main activities in development, instead of beeing the main activity itself.


问:
Do compilers have to be written for each model of CPU?
Do you need to take account of the different processors and their instructions when writing a compiler? Have instructions been standardised? Or what tools and techniques are available to assist with this? E.g. Ignoring machine instructions that are specific to a certain processor model.</p>

答:
A compiler is usually composed of many parts. Generating the actual code is just one part, and a small one.  So, to make a compiler for a new processor, you only need to make small changes to an old one.

Also, processors come in families. When (for example) Intel releases a new processor, it does everything the old processor does, and more.  This means that you can continue to use the existing compiler.  It will make programs that work on the new processor.  They will not use the new instructions that is offered, but they will still work.

For example, rather old compilers will only produce 32-bit programs.  The programs still run on new 64-bit computers, but they do not run well.

You probably want a new compiler to truely take advantage of the new chip, but it isn't necessary.


答:
"model driven software engineering (MDSE)" is the marketing promise of software tool manufacturers
that "soon" significant parts of software can be generated out of software-models.

The interview partner in the
article you are refering to
, Robert Howe is a tool manufacturer (see http://www.verum.com/ for details)

But against tool manufacturer-s promises mdse has not become mainstream yet.

The hybris internet shop system is a working example of "MDSE": you as a software developper maintain xml-model-files ("*-items.xml")
and codegenerators/interpreters generate db-modell/java-code for persistence/guis out of it. If you need an additional attribute just add it to the xml-model and after the generator/interpreter
has done it-s job you can use the attribute to implement the business logic.

Title: What exactly is model driven software engineering (MDSE)?

Body:
I came accross the accronym MDSE today on infoq, and the information I could find what quite unclear and the description was full of buzzwords :

MDSE is about enabling software engineers to work at a level of abstraction where requirements, architecture and design information is maximally ordered (in terms of information "entropy") and preserved. (Call this the "design work product"). Further, MDSE should provide engineers with the means to verify and validate their designs primarily terms of their "design work product"

And apparently, everyone is doing it: (from the article again)

We’re at the dawning of the age of MDSE. In the next 5 – 10 years we will see a significant shift towards MDSE, to the extent that I believe that by the end of this period perhaps 60 – 80% of software will be designed using model based techniques.

I would like to have a concrete, buzzword-free description of what MDSE is. Is it drawing UML boxes and generating code with it, like they did in the 90s with Rational Rose?

(while were at it, if anyone has an example of software generated using those techniques, I would really like to see a concrete example).


问:
Should I stop using the term C/C++?
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.

答:
Some programs are written in a mixture of C and C++

This is just a fact of life. You can compile object files from C and C++ and link them together. The result can quite reasonably be called "a C/C++ program".

But that's only the program as a whole. What about the individual compilation units?

There is a subset of C which is also a subset of C++

A program (or compilation unit) written in that subset will compile and behave the same under conformant C and C++ compilers. Such a program or file can rightly be called "a C/C++ program" or "a C/C++ file".

A partial program such as a header file may also be used in both C and C++ programs. Such header files can rightly be referred to as C/C++ headers.

Quoting Professor Bjarne Stroustrup:

Is C a subset of C++?

In the strict mathematical sense, C isn't a subset of C++. There are programs that are valid C but not valid C++ and even a few ways of writing code that has a different meaning in C and C++. However, C++ supports every programming technique supported by C. Every C program can be written in essentially the same way in C++ with the same run-time and space efficiency. It is not uncommon to be able to convert tens of thousands of lines of ANSI C to C-style C++ in a few hours. Thus, C++ is as much a superset of ANSI C as ANSI C is a superset of K&R C and much as ISO C++ is a superset of C++ as it existed in 1985.

Well written C tends to be legal C++ also. For example, every example in Kernighan & Ritchie: "The C Programming Language (2nd Edition)" is also a C++ program.

http://www.stroustrup.com/bs_faq.html#C-is-subset

So yes there is such a thing as C/C++. It's anything which is both valid C and valid C++.

The C pre-processor is part of the C language. The C++ pre-processor is part of the C++ language

You can write a compilation unit which will compile under C or C++ and be different. For example, it might have basic functionality compiled in C but take advantage of a C++ library if compiled in C++.

If the program is essentially the same, but with additional features, it's not exactly wrong to say it's the same program. Its the same, but also different.

Most C programmers can do at least a little C++ and vice-versa

It's not unreasonable to call such a person a C/C++ programmer. Yes, they probably specialise in one, but is there anyone who is a competent C or C++ programmer who literally cannot do any of the other language? In a way, aren't they all C/C++ programmers?

There's nothing wrong with saying "C/C++". What matters is being understood

The English language is not a tool for expressing syllogisms. You can use English for logic, but only just, and with great effort.

This is because words do not naturally have exact meanings, but rather a vague cloud of denotations and connotations. What matters is if people understand what you are saying.

OwnerDisplayName: redobot

Title: Should I stop using the term C/C++?


问:
Type checking as opposed to multiple functions?
In statically-typed languages such as Java, code such as the following is common (not much of a realistic example, I know):

```<code>public String flip(String text) {
    String result = "";
    for (int i = text.length() - 1; i >= 0; i++) {
        result += text.charAt(i);
    }
    return result;
}

public int flip(int value) {
    return (-1) * value;
}
</code>```

However in dynamic languages, there's no way to dispatch a specific method based on a parameter's type. So for example in Python 3, we'd have two options on how to do this. First is to check the type inside the function.

```<code>def flip(value):
    if isinstance(value, str):
        return value[::-1]
    elif isinstance(value, int):
        return (-1) * value
    else:
        raise TypeError('Expected str or int.')
</code>```

Second option is to have multiple functions:

```<code>def flip_int(value):
    return value * (-1)

def flip_str(text):
    return text[::-1]
</code>```

(In dynamic languages such as Python we should try to employ duck-typing, but I'm talking about cases where that's not possible, such as the example above).

Which option should I prefer, and why? Also, is there a 'best-practice' for this in Python?

I'm asking especially about Python, but this is relevant I believe to any dynamic language.

答:
Including the type name inside the function is vastly preferable because it allows the programmer to specify precisely what they intend. It also makes your code a lot easier to test. If you do want implicit dispatch depending on the type, you can always offer an optional wrapper. So I would write your code as:

```<code>def flip_int(x):
  return -x

def flip_str(x):
  return x[::-1]

def flip(x):
  if isinstance(x, int): return flip_int(x)
  if isinstance(x, str): return flip_str(x)
  raise TypError("flip(x) requires x to be int or str")
</code>```

Incidentally, you have effectively re-invented method dispatch. This run-time dispatch over function arguments is slightly different from “traditional” method dispatch in that the dispatch is handled by the function that is called, not by the value that the function is called on. In its generalization for more than one argument, this mechanism is known as multi-methods. The rest of this answer discusses argument-based method dispatch in the context of Java and Python.

Your Java example is exhibits function overloading, also known as ad-hoc polymorphism. In most languages, ad-hoc polymorphism is part of static dispatch, i.e. the overload is resolved at compile-time. When your declare two functions

```<code>String flip(String);
int flip(int);
</code>```

the compiler recognizes them as two distinct functions that happen to share a name. So the compiler would store it as something like

```<code>flip = flip_String | flip_int;
String flip_String(String);
int flip_int(int);
</code>```

When the compiler then parses a function call flip(x), it will first resolve the static type of x. Because flip is overloaded, it will try to see which overloads actually match. How that works depends on the exact rules of the language. E.g. some languages allow implicit conversions, so the types might not match exactly. In type systems with subtyping, a type will also match all its base types. This can cause multiple overloads to be legal call targets, so many languages have some kind of ranking method. E.g. calls that don't require conversions are preferred. With subtyping, the most specific type is preferred.

So finally, if the term x has type String, the overload flip_String would be chosen.

Of course, the static nature of this dispatch restricts its expressiveness. E.g. assume that class A inherits from B. We now have two functions void f(A) and void f(B). Given B b = new A(); f(b), the overload chosen will always be f(B) since that's the static type of the variable b, even if its runtime value is of the more specific type A.

Everything[1] that can be done statically in ahead of time compilation can also be done dynamically during runtime. While there might not be a static type in dynamic languages, the dispatch mechanism now has access to the precise dynamic type of a value. This means that runtime overload resolution can be more expressive than static resolution[1]: we can dispatch on the dynamic type of values. The mechanism is identical to the static version of the dispatch: the dispatch mechanism needs a set of available dispatch targets. When the overloaded function is called, the correct overload is selected.

[1]: Some languages allow return-type polymorphism, which is admittedly a bit difficult to do in dynamic languages unless the language is also lazy and supports symbolic execution.

This dynamic overload resolution is related to method dispatch. When we have a class A that is a subtype of class B and x is an instance of either of those classes, then x.foo() can do something entirely different depending on what its dynamic type is. The visitor pattern can be used to generalize this single dispatch to double dispatch, where a call x.visit(y) is resolved based on the dynamic type of both x and y. This can be generalized to multimethods, where a function is dispatched on the dynamic type of all its arguments.

Unsurprisingly, Python already has a package for multimethods:

```<code>from multimethods import multimethod

@multimethod(int)
def flip(x):
  return -x

@multimethod(str)
def flip(x):
  return x[::-1]

print(flip(42))
print(flip("foo"))
</code>```

Some languages use multimethods as their primary dispatch mechanism, e.g. the Common Lisp Object System, or the Julia language. However, most cases of polymorphism can be either resolved statically, or simplified to single dispatch. Therefore, built-in language support for multimethods tends to have negligible performance impact when compared with multimethods that are added to an existing language via metaprogramming.

Implementing multi-methods can be non-trivial, because two separate overloads might look like equally good candidates. Again, assuming that A is a subtype of B:

```<code>void foo(A, B);
void foo(B, A);
A x; A y;
foo(x, y);
</code>```

Both candidates would match equally well. There are various approaches to resolve this. One solution might be to find the overall “best” match using some kind of subtyping distance, but that tends to be hard to understand for programmers. It is more reasonable to look at all arguments from left to right, and order the overloads if one candidate is a better match for this single argument. E.g. in this example, the first argument is of type A, so foo(A, B) would be preferred over foo(B, A). The second argument matches both of these cases and does not change the existing order.

The mentioned Python module ignores these difficulties, and instead dispatches to the first match, no matter how well it actually matches.
This requires a user to put the more specific cases before the more general case. The module's main dispatch logic boils down to this:

```<code>def __call__(self, *args):
  for types, function in self.typemap:
    if len(args) == len(types) and all(isinstance(a, t) for a, t in zip(args, types)):
      return function(*args)
  raise ValueError("multimethod: no matching method found")
</code>```

You can see the full source yourself under r0k3/multimethods on GitHub, or install the module via pip install multimethods.

Body:
Including the type name inside the function is vastly preferable because it allows the programmer to specify precisely what they intend. It also makes your code a lot easier to test. If you do want implicit dispatch depending on the type, you can always offer an optional wrapper. So I would write your code as:

def flip_int(x):
  return -x

def flip_str(x):
  return x[::-1]

def flip(x):
  if isinstance(x, int): return flip_int(x)
  if isinstance(x, str): return flip_str(x)
  raise TypError("flip(x) requires x to be int or str")

Incidentally, you have effectively re-invented method dispatch. This run-time dispatch over function arguments is slightly different from “traditional” method dispatch in that the dispatch is handled by the function that is called, not by the value that the function is called on. In its generalization for more than one argument, this mechanism is known as multi-methods. The rest of this answer discusses argument-based method dispatch in the context of Java and Python.

Your Java example is exhibits function overloading, also known as ad-hoc polymorphism. In most languages, ad-hoc polymorphism is part of static dispatch, i.e. the overload is resolved at compile-time. When your declare two functions

String flip(String);
int flip(int);

the compiler recognizes them as two distinct functions that happen to share a name. So the compiler would store it as something like

flip = flip_String | flip_int;
String flip_String(String);
int flip_int(int);

When the compiler then parses a function call flip(x), it will first resolve the static type of x. Because flip is overloaded, it will try to see which overloads actually match. How that works depends on the exact rules of the language. E.g. some languages allow implicit conversions, so the types might not match exactly. In type systems with subtyping, a type will also match all its base types. This can cause multiple overloads to be legal call targets, so many languages have some kind of ranking method. E.g. calls that don't require conversions are preferred. With subtyping, the most specific type is preferred.

So finally, if the term x has type String, the overload flip_String would be chosen.

Of course, the static nature of this dispatch restricts its expressiveness. E.g. assume that class A inherits from B. We now have two functions void f(A) and void f(B). Given B b = new A(); f(b), the overload chosen will always be f(B) since that's the static type of the variable b, even if its runtime value is of the more specific type A.

Everything[1] that can be done statically in ahead of time compilation can also be done dynamically during runtime. While there might not be a static type in dynamic languages, the dispatch mechanism now has access to the precise dynamic type of a value. This means that runtime overload resolution can be more expressive than static resolution[1]: we can dispatch on the dynamic type of values. The mechanism is identical to the static version of the dispatch: the dispatch mechanism needs a set of available dispatch targets. When the overloaded function is called, the correct overload is selected.

[1]: Some languages allow return-type polymorphism, which is admittedly a bit difficult to do in dynamic languages unless the language is also lazy and supports symbolic execution.

This dynamic overload resolution is related to method dispatch. When we have a class A that is a subtype of class B and x is an instance of either of those classes, then x.foo() can do something entirely different depending on what its dynamic type is. The visitor pattern can be used to generalize this single dispatch to double dispatch, where a call x.visit(y) is resolved based on the dynamic type of both x and y. This can be generalized to multimethods, where a function is dispatched on the dynamic type of all its arguments.

Unsurprisingly, Python already has a package for multimethods:

from multimethods import multimethod

@multimethod(int)
def flip(x):
  return -x

@multimethod(str)
def flip(x):
  return x[::-1]

print(flip(42))
print(flip("foo"))

Some languages use multimethods as their primary dispatch mechanism, e.g. the Common Lisp Object System, or the Julia language. However, most cases of polymorphism can be either resolved statically, or simplified to single dispatch. Therefore, built-in language support for multimethods tends to have negligible performance impact when compared with multimethods that are added to an existing language via metaprogramming.

Implementing multi-methods can be non-trivial, because two separate overloads might look like equally good candidates. Again, assuming that A is a subtype of B:

void foo(A, B);
void foo(B, A);
A x; A y;
foo(x, y);

Both candidates would match equally well. There are various approaches to resolve this. One solution might be to find the overall “best” match using some kind of subtyping distance, but that tends to be hard to understand for programmers. It is more reasonable to look at all arguments from left to right, and order the overloads if one candidate is a better match for this single argument. E.g. in this example, the first argument is of type A, so foo(A, B) would be preferred over foo(B, A). The second argument matches both of these cases and does not change the existing order.

The mentioned Python module ignores these difficulties, and instead dispatches to the first match, no matter how well it actually matches.
This requires a user to put the more specific cases before the more general case. The module's main dispatch logic boils down to this:

def __call__(self, *args):
  for types, function in self.typemap:
    if len(args) == len(types) and all(isinstance(a, t) for a, t in zip(args, types)):
      return function(*args)
  raise ValueError("multimethod: no matching method found")

You can see the full source yourself under r0k3/multimethods on GitHub, or install the module via pip install multimethods.


问:
Stuck on design when attempting to create an object store
I'm working on a small scale API project but as it will be used and maintained by people that are not Software Engineers to trade I am attempting to keep the design as separate and identifiable as possible, using SOLID has made this easier.

But a few of my objects require to change (say made "active") which then in turn should make the other object that was "active" now disabled. This is simply a property of the object. This requires me to still know about all the objects even after they have been returned to the user.

So I've thought up that I can use an "Object Store" which will store the object's created before they are actually returned to the user of the system, but I'm unsure where in my pattern of creating objects that this sits. I've added an image below that shows how the objects are created within my solution.

So within my solution the controller get's the necessary properties to build an object (this may include interfacing externally but I've missed this out my diagram). This passes the arguments to the factory that then actually builds the object.

So I was thinking of adding to my "object store" in the controller after it has requested the factory to build the object, but the issue with this is that it then means that the controller will be responsible for, getting the necessary arguments and storing the created objects.

I was also thinking that it could be placed between the controller and the factory so that the controller said "GetObject" on the "object store" and this could save it internally but this then means that the object store won't just store objects it will also request for them to be built.

Is there any pointers on where this could sit and why? Perhaps my pattern for creating objects is incorrect (seems to have been OK up to now)?

Specifics so what I am doing is an adapter that sits over the ActiveX interface of Third-party software that my Company uses. This will be used as an API by other "engineers" within the company for automating tasks that the third party software does. As object "X" in my example returns a collection of "Y"'s I am looking for a method of changing a property on the other Y's when one changes, like a "active" flag, one is made active the current active is dis-activated. I don't know how much more specific I can be without saying exactly what the application is or does.

答:
In Cases where you have a property on an object which is dependent on other objects in a group. It can sometimes be a good idea to move this to be a property of the group, rather than a property of each object.

eg

say we have an eCommerce system where customer have accounts with multiple credit cards. However only one one credit card is active at a time.

instead of:

```<code>CreditCard.IsActive
</code>```

We could instead have

```<code>Account.ActiveCardId
</code>```

This will enforce the 'only one at a time' nature of Active and allow you to use each CreditCard as an invariant data object.

Body:
In Cases where you have a property on an object which is dependent on other objects in a group. It can sometimes be a good idea to move this to be a property of the group, rather than a property of each object.

eg

say we have an eCommerce system where customer have accounts with multiple credit cards. However only one one credit card is active at a time.

instead of:

CreditCard.IsActive

We could instead have

Account.ActiveCardId

This will enforce the 'only one at a time' nature of Active and allow you to use each CreditCard as an invariant data object.


问:
Should the View not perform validation?
I was reading "In MVC should a model handle validation?" because I was curious about where validation logic should go in an MVC website. One line in the top answer goes like this: "controllers should handle validation, models should handle verification."

I liked that, but it left me wondering why we wouldn't do data validation in the View, for several reasons:

Views typically have robust validation support (JS libraries, HTML5 tags)

Views can validate locally, reducing network IO

UI is already designed with data-type in mind (calendars for dates, spinners for numbers), making it one small step from validation

Validating in more than one place is contrary to MVC's concept of isolating responsibilities, so "do it in both" seems inappropriate. Is doing data validation only in the controller truly the dominant approach?

答:
For many developers, Fat models against Stupid Ugly Controllers is preferred method.

Base concept in the text is

... So always remember that the Model is not just the database. Even the data you get from web services can be expressed as a Model! Yes, even Atom feeds! Frameworks which rattle off introductions to the Model, almost never explain this upfront which only exacerbates misunderstandings.

and

The View should only be concerned with generating and presenting a UI so users can communicate intent to the Model. Controllers are the orchestrators who translate UI inputs into actions on the Model and pass back output from whatever View has been made aware of the Model(s) its presenting. Controllers must define application behaviour only in the sense that they map user input onto calls in Models, but beyond that role it should be clear all other application logic is contained within the Model. Controllers are lowly creatures with minimal code who just set the stage and let things work in an organised fashion.

The View should only be concerned with generating and presenting a UI so users can communicate intent to the Model is the important part. A model should define de stored data, so it must also be responsible for checking the validity of the data.

When taking the record of a person, each person must have a unique ID number given by the country. This check (generally) is done by the UNIQUE key  check by the database. Each given ID number should satisfy some control steps (sum of odd digits should be equal to sum of even digits etc). This types of controls should be done by the Model

Controller is collecting data from Model and pass it to View, or reverse, collect the user data through View and pass it to Model. Any restriction of accessing the data and validating it should not be done by the Controller. It was the Controller who collects the cookie data and it was the Model which checks if it is a valid session or the user have access to this part of the application.

View is the user interface that collect data from user or present data to user. Simple checks can be done by the View like the user input e-mail address or not (thus this can also be done in the View) IMO.

View is the client side, and you should not thrust the user input. Javascripts may fail to run on the client side, a user can use handwritten scripts to alter them or disable the script using the browser. You can set client-side validation scripts, but never you should never thrust them and
make the real check on the Model layer.

Title: Should the View not perform validation?


问:
How do you look for programmers when your project's not in a particularly popular language?
So, we've got a product, written in Perl. Mind you, it's good Perl, pretty well object-oriented, with a strong functional-programming influence, extensive test suites, and it's an agile environment doing Extreme Programming with elements of Scrum.

We also have about 4 open headcount that we're trying to fill sooner rather than later, and we've historically had trouble filling even just one or two. I've been taking a look at the sort of candidates that our existing postings seem to be attracting, and they're not particularly impressive. Most of them have a background in QA automation or something similar.

We know that we can take good OO software engineers who know Python or Ruby or even just C++/Java and bring them up to speed quickly enough. We're pretty good at being able to pitch the actual job itself to qualified candidates if we have their ear. What we're not good at, it seems, is attracting these people to our postings in the first place.

What sort of things can we do to market ourselves to these engineers?

What sort of things should we be careful to avoid in job postings and the like?

(The posting is omitted since I don't want to get in any trouble by doing an end-run around the job-board. Also, our current in-house recruiter isn't helping much.... rumors are his days are numbered and I'm not at all surprised...)

答: Consider the nearest Perl Users Group.</p>

ContentLicense: CC BY-SA 2.5

Body: Consider the nearest Perl Users Group.


问:
OO Pattern for making multiple versions of domain logic available to the client
I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time.

The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that version would have made.

I would use a facade and/or adapters or similar so the application's main code can switch between which versions of the module it uses without too much trouble.

As for the module, I was planning to use namespacing for each major revision (where the domain logic produces different results); duplicating all the classes in that domain logic module. I.e. effectively copy-and-paste the entire thing, including classes within the module that haven't changed.

This is a pungent code smell and I can't think of any way round it, let alone a simple way, given that the module may also undergo complete restructuring.

Any ideas?

答: Preserve an external API over time. Even if it's subpar, make it consistent. Then, build a factory that accepts a date (or version number) and returns the appropriate implementation, with the same consistent API.</p>


答:
I'm wondering why you would WANT to do that. If your requirement is to display the result of your previous domain logic, you might be better off to simply store the output in some immutable form and display it.

For example, let's assume you are building a system that does price calculations for orders and these calculations are subject to government regulation and, hence, might change over time. It is a lot easier to simply store the previous orders as a PDF, for example, rather than recalculate the results every time. (In fact, from some legal standpoints this might even be a requirement)

If you have thought long and hard about your implementation and you find that you DO need to re-run the logic, isolate it in a separate library. Annotate your data so you know what library to run it against. Create a facade that you can pass data through and does the switching between different versions of the library. Using version control you just tag the version of the library, build your library, deploy and move on. There will never be a need to go back and change a previous version of a library because you always need to keep the old logic going. Simply code your changes onto the code as-is and use source control to look back at previous versions should the need arise.

Title: OO Pattern for making multiple versions of domain logic available to the client

Body:
I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time.

The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that version would have made.

I would use a facade and/or adapters or similar so the application's main code can switch between which versions of the module it uses without too much trouble.

As for the module, I was planning to use namespacing for each major revision (where the domain logic produces different results); duplicating all the classes in that domain logic module. I.e. effectively copy-and-paste the entire thing, including classes within the module that haven't changed.

This is a pungent code smell and I can't think of any way round it, let alone a simple way, given that the module may also undergo complete restructuring.

Any ideas?


问:
Design pattern for wrapping logging around execution

Introduction

I am implementing a abstract Java class of a processing framework*. By implementing the function execute, I am able to add business logical functionality. I would like to add logging at the start and end of every implementation of every of my execute functions. Also in between some logging, if specific things are done. However, I would like to make this in a uniform manner. My thought was to inherit the framework class to an own new class which implements the logging and provides some new executeWithLogging functions, which are wrapping the logging around the specific parts. I am not sure if that is the best idea and whether I am able to use a design pattern that would make the whole endeavor elegant. How would I go on about the whole thing?

Challenges (please consider these!)

One challenge in my case is that the original class has only one execute function, however, I'd need logging around multiple parts.

The second thing is: Using a decorator pattern (was my first idea as well) does not quite work, if I am using also a execute, because the super.execute()-function would have to be called in the first line of my new execute(), isn't it?

There would be at least 4 classes involved: BaseFunction from the framework, LoggingFunction extends BaseFunction from me, MyBusinessFunction extends LoggingFunction from me, MyBusinessClass which instanciates MyBusinessFunction.

Not only do I need logging at the beginning and end of execute, but also in the middle.

The "logging" is not just simple Java logging, but actually logging to a database. This does not change anything about the principles, but demonstrates that the logging might be more than just one line of code.

Maybe an example how I'd do the whole thing would be nice, to get me going.

|* A Storm Trident Function, similar to a Storm bolt, but this is not particularly important.

答: Your approach seems valid and is actually an implementation of the Decorator Pattern. There are other ways you could do this I suppose, but Decorator is a very elegant and easy to understand pattern that is very suited to solving your problem.</p>


答:
There are generally several possible ways to perform logging around a certain execution. First of all, it is good that you want to separate this, as logging is a typical example for Separation of Concerns. It truly doesn't make much sense to add logging directly into your business logic.

As for possible design patterns, here is a (non-conclusive) list from the top of my head:

Decorator pattern: A well-known design pattern, whereby you basically wrap the non-logging class into another class of the same interface and the wrapper does the logging before and/or after calling the wrapped class.

Function composition: In a functional programming language, you can simply compose your function with a logging function. This is similar to the decorator pattern in OO languages, but not a preferred way really, since the composed logging function would be based on a side-effecting implementation.

Monads: Monads are also from the functional programming world and allow you to decouple your execution and logging. This basically means you aggregate necessary logging messages and executions methods, but do not yet execute either. You can then process the monad in order to perform log-writing and/or actual execution of the business logic.

Aspect-oriented programming: More sophisticated approach, which achieves complete separation, as the class that does the non-logging behavior never directly interacts with the logging.

Relaying: Other standard design patterns may be suitable as well, for example, a Facade could serve as the logged entrypoint, before forwarding the call to another class which performs the business logic part. This can be applied to different abstraction levels as well. For example, you could log requests made to an externally reachable service URL, before relaying to an internal URL for actual non-logged processing of requests.

As for your added requirement that you need to perform logging "in the middle" - that's probably pointing to a strange design. Why is it, that your execute is doing so much, that something like a "middle" of its execution is even remotely of interest? If there is indeed such a lot of stuff going on, then why not bunch it up into stages/phases/what-have-you? You could in theory achieve logging in the middle with AOP I guess, but I'd still argue that a design change seems to be much more appropriate.

Title: Design pattern for wrapping logging around execution

Body:
Introduction

I am implementing a abstract Java class of a processing framework*. By implementing the function execute, I am able to add business logical functionality. I would like to add logging at the start and end of every implementation of every of my execute functions. Also in between some logging, if specific things are done. However, I would like to make this in a uniform manner. My thought was to inherit the framework class to an own new class which implements the logging and provides some new executeWithLogging functions, which are wrapping the logging around the specific parts. I am not sure if that is the best idea and whether I am able to use a design pattern that would make the whole endeavor elegant. How would I go on about the whole thing?

Challenges (please consider these!)

One challenge in my case is that the original class has only one execute function, however, I'd need logging around multiple parts.

The second thing is: Using a decorator pattern (was my first idea as well) does not quite work, if I am using also a execute, because the super.execute()-function would have to be called in the first line of my new execute(), isn't it?

There would be at least 4 classes involved: BaseFunction from the framework, LoggingFunction extends BaseFunction from me, MyBusinessFunction extends LoggingFunction from me, MyBusinessClass which instanciates MyBusinessFunction.

Not only do I need logging at the beginning and end of execute, but also in the middle.

The "logging" is not just simple Java logging, but actually logging to a database. This does not change anything about the principles, but demonstrates that the logging might be more than just one line of code.

Maybe an example how I'd do the whole thing would be nice, to get me going.

|* A Storm Trident Function, similar to a Storm bolt, but this is not particularly important.


问:
Preventing unauthorized writing to parts of server
Say I have two members which share a server. Both members have a game that is accessible to anyone and after playing, it records high scores by sending a request to write to a file on the server. However game A should only be allowed and to write to its own file as well as game B. Is there any way to authenticate which game/file is making the request to write to the file. Say maybe when the game file is requested from the server, I could add a unique token with it that identifies it and if tampered with, would invalidate it.</p>

答:
You did not specify which operating system you are using, and which protocol should be used between clients. As mentioned in the comment by Bart best thing is to create different user accounts.

You marked the question with http-request, so if the protocol shall be HTTP, you should look into learning more about WebDAV protocol, which will allow you to store/retrieve files to/from a server using http.


问:
Why do XSLT editors insert tab or space characters into XSLT to format it?
All XSLT editors I've tried till now add tab or space characters to the XSLT to indent it for formatting. This is done even in places within the XSLT where these characters are significant to the XSLT processor.

XSLT modified for formatting in this way can produce output very different to that of the original XSLT if it had no formatting. To prevent this, xsl:text elements or other XSLT must be added to a sequence constructor to help separate formatting from content, this additional XSLT impacts on maintainability. Formatting characters also adversely impact on general usability of the tool in a number of ways (this is why word-processors don't use them I guess) and add to the size of the file.

As part of a larger project I've had to develop a light-weight XSLT editor, it's designed to format XSLT properly, but without tab or space characters, just a dynamic left-margin for each new line. The XSLT therefore doesn't need additional elements to separate formatting tab or space characters from content. The problem with this is that if XSLT from this editor is opened in other XSLT editors, characters will be added for formatting reasons and the XSLT may therefore no longer behave as intended.

Why then do existing XSLT editors use tabs or spaces for formatting in the first place?

I feel there must be valid reasons, perhaps historical, perhaps practical. An answer will help me understand whether I need to put compatibility options in place in my XSLT editor somehow, whether I should simply revert to using tabs or spaces for both XSLT content and formatting (though this seems like a backwards step to me), or even whether enough XSLT users might be able to persuade their tools vendors to include alternative formatting methods to tabs or spaces.

Note: I provided an XSLT sample demonstrating formatting differences in this answer to the question: Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?

答: Everyone building editors for the last 20 years has started from the perspective of vi, Emacs, Visual Studio, or one of their equivalents.  Back in 1985, when Mike Cowlishaw wrote one of the first SGML editors (LEXX) for the Oxford English Dictionary's digitalization project, he did exactly what your XSLT editor does - separate visualization from representation.  It's a shame that never really caught on.</p>


答:
Emphasize more on the nature and impact of your project, but less on the language itself.

Some of the QA Automation candidates may actually fit in your project. You may be able to devise a strategy that can identify the right one. With that strategy in mind, you will not need to reject them on the basis of backgrounds.

Title: How do you look for programmers when your project's not in a particularly popular language?

Body:
So, we've got a product, written in Perl. Mind you, it's good Perl, pretty well object-oriented, with a strong functional-programming influence, extensive test suites, and it's an agile environment doing Extreme Programming with elements of Scrum.

We also have about 4 open headcount that we're trying to fill sooner rather than later, and we've historically had trouble filling even just one or two. I've been taking a look at the sort of candidates that our existing postings seem to be attracting, and they're not particularly impressive. Most of them have a background in QA automation or something similar.

We know that we can take good OO software engineers who know Python or Ruby or even just C++/Java and bring them up to speed quickly enough. We're pretty good at being able to pitch the actual job itself to qualified candidates if we have their ear. What we're not good at, it seems, is attracting these people to our postings in the first place.

What sort of things can we do to market ourselves to these engineers?

What sort of things should we be careful to avoid in job postings and the like?

(The posting is omitted since I don't want to get in any trouble by doing an end-run around the job-board. Also, our current in-house recruiter isn't helping much.... rumors are his days are numbered and I'm not at all surprised...)


问:
TDD: How to test domain model
When practicing TDD, how do you test a domain model?  If you don't test, how do you account for code coverage?  We want to have 100% coverage (or as much as possible), but despite hours of training videos we cannot find the best solution.

UPDATE:  Given a domain model I want to write of User which has properties: Id (primary key), FirstName, LastName, tenantId(foreign key).  Do you prefer to just create this model without test coverage?  If so, then you start your project with 0% code coverage, right?  Then you are getting off to a rough start.  But in pure TDD, you should not write code without a test.  So what would you do?

Let's take this a step further.  What if you have behavior--but just a little?  Now your User has Id (primary key), FirstName, LastName, tenantId (foreign key) and birthDate.  Then you have a method/function to calculate age based on birthdate.  I feel that I should write tests before the age calculation, but not before the model.  How would you account for this paradox?

答:
This is why code coverage is a terrible metric.

If you have a simple DTO (a class with only properties that contains data), there is very little value in testing the methods that get and set those properties. You can, and your code coverage will surely go up, but it's a useless test. You're testing the language and not the code. If you strive for a good coverage, strive for coverage of code that actually does something.

The 'only write code to make a failing test pass' is a very good rule, but it is not meant to be invoked at every turn. In fact, even constructors are evil so we probably should never use them, right? Well, not really. But it is a lot easier (and catchier) to say 'never' instead of 'mostly never, unless...'. The rule that you should never write code unless it is written to make a failing test pass is the same.

With time and application of TDD to your development comes an amount of experience with it that allows you to see where the rule should be enforced and where it should not be enforced.

Title: TDD: How to test domain model


问:
gitflow model with UAT releases is too chaotic, how to simplify?
At $DAYJOB, we have the following release/delivery pipeline:

Get new features, work on new features.

Once all features are completed, our own QA performs regressions, etc.

QA signs off on first UAT build, ships to customer UAT department (this is really customer's own QA force). This begins our initial version (e.g. v1.0)

Customer QA (UAT) finds issues, sends us back a list.

Development addresses the list of issues. Sometimes they might ask for non-defects, such as improvements or small features. We triage these on a case-by-case basis. Our own QA also verifies the fixes. They sign off, we ship a new build (this gets a version bump, like v1.1)

This "get list" and "work on the list" process cycles a few times, until customer signs off on the build (UAT Pass).

Signed-off build becomes "production". Now developers can start working on new features for the next release.

Some notes on this process:

We use a bastardized version of git-flow for this process (will explain in more detail later).

Regarding versioning, we do not differentiate between UAT releases and production releases. We have to assume any release to UAT might be signed off and go gold at any time. For us, each build "out the door" is treated as a "production release".

Developers work on branches off of develop for new features. We even work on features for the next release. However, we do not merge features until they are scheduled for release. This is because we do not create 'release' branches (more on this later).

Here is how our development process goes for both bugs and features:

Developer branches off develop and begins work.

Developer finishes work, performs code review

Code review passes, and we indicate to QA the branch is ready for testing. Our CI build system builds every branch in the remote repository, and QA can grab ad-hoc builds off of any branch. QA tests features in branches (and not off of develop) for a few reasons:

Builds on develop might include multiple features or bug fixes from multiple developers over the course of some time. When regressions occur, it becomes more difficult to track down what caused the regressions. The "test-each-branch" model allows us to isolate regressions to the changes on that branch (i.e. the one feature or bugfix).

All features must be tested on a branch because we do not merge them into develop until QA is happy with it. Also QA controls deployment schedule, so they know when develop is ready for new features.

We're tight on QA resources. At the moment we have a 4-to-1 ratio of developers to QA personnel. They simply can't keep up with the work we do.

Once QA is happy with the feature on the branch, they mark it as "verified".

Once verified, it sits there unchanged until someone with appropriate authority "approves" the feature or branch. At this point, a developer rebases/merges latest into the branch, fixes conflicts, then merges it into develop.

When we finally release software (new UAT build usually), we do a merge from develop directly into master.

Symptoms of the current system:

Tons of branches sitting around waiting to be merged. Over 100 at the moment, and the turnaround time is sometimes months before they are merged.

Process is complex and tightly controlled by QA

Throw submodules into the mix and you've got a recipe for disaster and complexity.

The reason we don't use the release branches right now is because we've had a bad experience with them. UAT process can sometimes take months. Sometimes they request features, unreasonably, and upper management allows it. We've had our release branches become numerous, long-lived, with huge parity issues (in other words, they accumulate tons of changes over their lifetime).

This whole thing is pretty chaotic and tough to manage. However, QA gives us a ton of great feedback on this process because our releases are super stable. This is because QA touches every branch before it is merged, whereas before developers merged all day long to develop and QA couldn't keep up with the changes, so a bunch of stuff went untested in releases.

Now that I've explained our process and situation, some questions:

How can we simplify this process?

How should release branches be handled when you have UAT process in the middle? Ideally we want to be able to continue active development on develop after UAT starts.

答:
Ultimately we decided to go with a release branch per physical release out the door, regardless of how the customer intended to use it. If a released build happens to never make it through UAT, that's OK, we'll create another release branch and ship again. However, if UAT does accept the build, we do not get an opportunity to build it again. In that case they keep the build they got and we move on with the next release that may not be related to UAT at all.

In this respect, all of our releases follow the exact same flow and rules. I suspected we would be creating several release branches a week during UAT cycles but that is not the case. Our QA teams spend sufficient time on a release branch that we're only creating one every 2+ weeks.

So far this is working out great and is very manageable. It also forces feature releases to wait on UAT releases to complete, which is great. We can handle releases at a more granular level.


问:
Does Semantic Versioning allow 4 components in version numbers?
All examples of semantic versioning I've seen show 3 components in use. No more than 2 period characters. At $DAYJOB, we use 4 components in our release numbers:

```<code>5.0.1.2
</code>```

Does Semantic Versioning allow for this?

And as a higher-level and more arguable side question, does it really even matter? I started to think it might be a good idea to enforce semantic versioning, but ultimately entities like PCI override it.

I should have clarified on my PCI comment. The issue is that audits and their cost influence when the major and minor components change, not necessarily a true new feature. For example, if a feature related to payments is introduced, we bump the minor number for PCI. But if we add a brand new feature related to something in the gui, it doesn't. Only the patch changes. So in this case we don't really get a say in the matter as developers since someone else makes those decisions.

答:
It sounds like you are bypassing normal conventions just to avoid process overhead/audits. That... strikes me as concerning.

What you are doing is effectively making an extra version number (your minor PCI digit) somewhat intentionally in order to move your feature/minor version numbers back a place, to no longer trigger your internal audit criteria.

Anyways, getting to your question about semantic versioning, the spec for Semantic Versioning states:

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

MAJOR version when you make incompatible API changes,

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

PATCH version when you make backwards-compatible bug fixes.

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

Emphasis mine.

So the question is, are you using the fourth character for pre-release/build metadata? Or is it basically another version indication that you are releasing?

If "yes" then semantic versioning's spec does allow for it. If "no" then you technically are not following semantic versioning.

And as a higher-level and more arguable side question, does it really even matter?

Whether you want to rigidly follow it or not is a decision you and your team have to make. The purpose of semantic versioning is to help with API compatibility:

Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

I call this system "Semantic Versioning." Under this scheme, version numbers and the way they change convey meaning about the underlying code and what has been modified from one version to the next.

It's a system that helps make it more clear when versioning affects downstream users of the API.

As long as your API is similarly clear it's not a huge deal which way you choose. Semantic versioning just happens to be straightforward, for example  if I'm using 3.4.2 and need to upgrade to 3.4.10 I know I can do so without breaking anything. If the new version is 3.5.1 I know it's backwards compatible. And I know version 4.0.1 would be a breaking change.

That's all part of what the version numbers mean.

@enderland Yes basically. MAJOR(PCI).MINOR(PCI).FEATURE.HOTFIX+BUILD. We're basically only allowed to change the 3rd and 4th component without getting PCI (and subsequently the PCI overlords at the company) involved. To me it feels like this is a bit contrived, I am not sure they are justified in the way they manage the version number, but I do not know enough about PCI and audit process to say otherwise.

Ok, this is fine. You have a system which works for you and meets your needs. That's the point of versioning.

If your API is private (only internally facing) it really doesn't matter how you version as long as it makes sense to you and everyone using it. Where versioning in a standard format matters is when you have many other consumers of your API that need to know "what does this version mean?"

Having an arbitrary versioning system will confuse people who are used to other systems, such as semantic versioning. But if no-one is really using your versioning system except the people creating it - it doesn't really matter.


问:
How to solve this inheritance problem
I have the following classes:

```<code>public abstract class StaticFileController<File, QueryData> : AsyncController
{
     private string _resourceName;

     public StaticFileController(string resourceName)
     {
          _resourceName = resourceName;
     }

     //This method receives _resourceName
     protected virtual void DoSomething(string resource)
     {
         //...
     }
}

public class ScriptController : StaticFileController<FileEntity, ScriptQueryData>
{
     public ScriptController : base("scripts") { }
}

public class StyleController : StaticFileController<FileEntity, StyleQueryData>
{
     public StyleController : base("styles") { }
}
</code>```

Now, let's suppose I have this class:

```<code>public class ScriptBundleController : ScriptController
{
     protected override void DoSomething(string resource)
     {
         // Use resource name and do something (~50 lines of code)
     }
}
</code>```

If I want to create a similar class for StyleController, I would have to create a new class (with the exact same implementation):

```<code>public class StyleBundleController : StyleController
{
     protected override void DoSomething(string resource)
     {
         // Use resource name and do something (~50 lines of code)
     }
}
</code>```

This troubles me because it seems I am duplicating code, which will give me problems in the future.

How can I solve this problem? I want to have my implementation written only in one place. I understand that two classes would likely be needed, such as ScriptBundleController and StyleBundleController but I want the DoSomething() method to be centralized in just one class.

答:
Instead of basing your inheritance on methods which are common in this case it may make more sense to have an outside helper class which contains methods your Controllers can use:

```<code>public class FileHelper
{
    public YourReturnTypeIfAny Minify(YourParameters params)
    {
        // your minify logic
    }
}
</code>```

Then you can call Minify() from your DoSomething() methods in your StaticFileControllers

Title: How to solve this inheritance problem

Body:
Instead of basing your inheritance on methods which are common in this case it may make more sense to have an outside helper class which contains methods your Controllers can use:

public class FileHelper
{
    public YourReturnTypeIfAny Minify(YourParameters params)
    {
        // your minify logic
    }
}

Then you can call Minify() from your DoSomething() methods in your StaticFileControllers


答:
The Answer is you cant do exactly this. If you think about it you would be effectively exposing private variables.

say we can do something like :

```<code> public class ScriptBundleController : ScriptController
    {
        protected override void DoSomething(string resource)
        {
            ((BundleController<FileEntity, ScriptQueryData>)this).DoSomething(resource);
        }
    }
</code>```

re casting the object to something outside its inheritance chain in order to give our apply our new DoSomething Function to the current object.

But DoSomething in BundleController can access the private variables of BundleController and hence ScriptBundleController and change them, which is exactly what setting them to private is supposed to stop!

you can do it if you change the inheritance chain and insert BundleController between your script/style controllers and the base class, passing the generic types down. But this isn't quite the same functionality, because DoSomething could be overridden in the script/style controllers .

eg.

```<code>public class StyleController : BundleController<FileEntity, StyleQueryData>
{
     public StyleController() : base("styles") { }
}

public class BundleController<T1, T2> : StaticFileController<T1, T2>
{
    public BundleController(string resourceName)
        : base(resourceName)
    { }

    protected override void DoSomething(string resource)
    {
        // Use resource name and do something (~50 lines of code)
    }
}
</code>```

Title: How to solve this inheritance problem

Body:
I have the following classes:

```<code>public abstract class StaticFileController<File, QueryData> : AsyncController
{
     private string _resourceName;

     public StaticFileController(string resourceName)
     {
          _resourceName = resourceName;
     }

     //This method receives _resourceName
     protected virtual void DoSomething(string resource)
     {
         //...
     }
}

public class ScriptController : StaticFileController<FileEntity, ScriptQueryData>
{
     public ScriptController : base("scripts") { }
}

public class StyleController : StaticFileController<FileEntity, StyleQueryData>
{
     public StyleController : base("styles") { }
}
</code>```

Now, let's suppose I have this class:

```<code>public class ScriptBundleController : ScriptController
{
     protected override void DoSomething(string resource)
     {
         // Use resource name and do something (~50 lines of code)
     }
}
</code>```

If I want to create a similar class for StyleController, I would have to create a new class (with the exact same implementation):

```<code>public class StyleBundleController : StyleController
{
     protected override void DoSomething(string resource)
     {
         // Use resource name and do something (~50 lines of code)
     }
}
</code>```

This troubles me because it seems I am duplicating code, which will give me problems in the future.

How can I solve this problem? I want to have my implementation written only in one place. I understand that two classes would likely be needed, such as ScriptBundleController and StyleBundleController but I want the DoSomething() method to be centralized in just one class.

Body:
The Answer is you cant do exactly this. If you think about it you would be effectively exposing private variables.

say we can do something like :

 public class ScriptBundleController : ScriptController
    {
        protected override void DoSomething(string resource)
        {
            ((BundleController<FileEntity, ScriptQueryData>)this).DoSomething(resource);
        }
    }

re casting the object to something outside its inheritance chain in order to give our apply our new DoSomething Function to the current object.

But DoSomething in BundleController can access the private variables of BundleController and hence ScriptBundleController and change them, which is exactly what setting them to private is supposed to stop!

you can do it if you change the inheritance chain and insert BundleController between your script/style controllers and the base class, passing the generic types down. But this isn't quite the same functionality, because DoSomething could be overridden in the script/style controllers .

eg.

public class StyleController : BundleController<FileEntity, StyleQueryData>
{
     public StyleController() : base("styles") { }
}

public class BundleController<T1, T2> : StaticFileController<T1, T2>
{
    public BundleController(string resourceName)
        : base(resourceName)
    { }

    protected override void DoSomething(string resource)
    {
        // Use resource name and do something (~50 lines of code)
    }
}


答:
In the current version of Semantic Versioning, which is 2.0.0, no. There is a requirement that defines the version as the form X.Y.Z where X, Y, and Z are non-negative integers that do not contain leading 0s:

A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically. For instance: 1.9.0 -> 1.10.0 -> 1.11.0.

However, the ability to add metadata is allowed for:

Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Build metadata SHOULD be ignored when determining version precedence. Thus two versions that differ only in the build metadata, have the same precedence. Examples: 1.0.0-alpha+001, 1.0.0+20130313144700, 1.0.0-beta+exp.sha.5114f85.

Something important to note, though, is that Semantic Versioning is specifically for software that declares a public API:

Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it should be precise and comprehensive.

This tends to support the development of libraries or services and not at an application level.

The important thing to consider is what your version numbers mean, both to internal and external use. Versions are just identifiers that allow you to talk about differences in software at two different points in time. Semantic Versioning is one method of putting rules around this, so if you know that an application is using Semantic Versioning, then you can more easily determine the level of effort required to update your packages. Following a common standard may be good, but if you can't for any reason, documenting the rules for your users should also be sufficient.

Title: Does Semantic Versioning allow 4 components in version numbers?

Body:
All examples of semantic versioning I've seen show 3 components in use. No more than 2 period characters. At $DAYJOB, we use 4 components in our release numbers:

```<code>5.0.1.2
</code>```

Does Semantic Versioning allow for this?

And as a higher-level and more arguable side question, does it really even matter? I started to think it might be a good idea to enforce semantic versioning, but ultimately entities like PCI override it.

I should have clarified on my PCI comment. The issue is that audits and their cost influence when the major and minor components change, not necessarily a true new feature. For example, if a feature related to payments is introduced, we bump the minor number for PCI. But if we add a brand new feature related to something in the gui, it doesn't. Only the patch changes. So in this case we don't really get a say in the matter as developers since someone else makes those decisions.


答:
I have the feeling that you absolutly want to use a pattern. Remember that a bad usage of design patterns may result in a code less maintainable/readable.

That beeing said...

Your case is tricky as it seems you want to do 2 kinds of logging:

Logging some steps of your logical functionality (inside execute)

Logging around function calls (entering/exiting a function) (outside execute)

For the first case, at the moment you want to log some things inside a function, you have to do it... inside the function. You could use the template method pattern to make things a bit prettier but I think it's overkill in this case.

```<code>public final class MyBusinessFunction extends BaseFunction {
    @Override
    public final void execute() {
        log.info("Initializing some variables");
        int i = 0;
        double d = 1.0;

        log.info("Starting algorithm");
        for(...) {
            ...
            log.info("One step forward");
            ...
        }
        log.info("Ending algorithm");

        ...
        log.info("Cleaning some mess");
        ...
    }
}
</code>```

For the second case, the decorator pattern is the way to go:

```<code>public final class LoggingFunction extends BaseFunction {
    private final BaseFunction origin;

    public LoggingFunction(BaseFunction origin) {
        this.origin = origin;
    }

    @Override
    public final void execute() {
        log.info("Entering execute");
        origin.execute();
        log.info("Exiting execute");
    }
}
</code>```

And you could use it like this in BusinessClass:

```<code>public final BusinessClass {
    private final BaseFunction f1;

    public BusinessClass() {
        this.f1 = new LoggingFunction(new MyBusinessFunction());
    }

    public final void doFunction() {
        f1.execute();
    }
}
</code>```

A call to doFunction will log this:

```<code>Entering execute
Initializing some variables
Starting algorithm
One step forward
One step forward
...
Ending algorithm
Cleaning some mess
Exiting execute
</code>```

Body:
I have the feeling that you absolutly want to use a pattern. Remember that a bad usage of design patterns may result in a code less maintainable/readable.

That beeing said...

Your case is tricky as it seems you want to do 2 kinds of logging:

Logging some steps of your logical functionality (inside execute)

Logging around function calls (entering/exiting a function) (outside execute)

For the first case, at the moment you want to log some things inside a function, you have to do it... inside the function. You could use the template method pattern to make things a bit prettier but I think it's overkill in this case.

public final class MyBusinessFunction extends BaseFunction {
    @Override
    public final void execute() {
        log.info("Initializing some variables");
        int i = 0;
        double d = 1.0;

        log.info("Starting algorithm");
        for(...) {
            ...
            log.info("One step forward");
            ...
        }
        log.info("Ending algorithm");

        ...
        log.info("Cleaning some mess");
        ...
    }
}

For the second case, the decorator pattern is the way to go:

public final class LoggingFunction extends BaseFunction {
    private final BaseFunction origin;

    public LoggingFunction(BaseFunction origin) {
        this.origin = origin;
    }

    @Override
    public final void execute() {
        log.info("Entering execute");
        origin.execute();
        log.info("Exiting execute");
    }
}

And you could use it like this in BusinessClass:

public final BusinessClass {
    private final BaseFunction f1;

    public BusinessClass() {
        this.f1 = new LoggingFunction(new MyBusinessFunction());
    }

    public final void doFunction() {
        f1.execute();
    }
}

A call to doFunction will log this:

Entering execute
Initializing some variables
Starting algorithm
One step forward
One step forward
...
Ending algorithm
Cleaning some mess
Exiting execute


问:
Is MVC now the only way to write PHP?
Hey... its XMAS Eve and something is bugging me... yes, I have work on my mind even when I am on holiday. The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.

I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.

So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?

答:
Well there are a lot of other approaches.

MVC is just popular because it suits most situations (or better said can be used in most situations) and has established itself as a de-facto standard.

What can be said is that every programming/design pattern - or more specific architectural - depends on some classification.

Those are often (of course they can be devided further):

User Interface (pretty images, forms etc)

Application (your application logic and stuff that needs to be secured from the client - ak lot of that can often be done in the user inteface, eg. by javascript)

Database - self explaining

Infrastructure (very basic stuff like hard disk, server systems, network etc.)

Of course there is always the naive, procedural straight-forward approach but also a lot fo other patterns that can link and structure the access and controlling to these basic layers.

Mvc is one of them. But here are some example of others:

http://en.wikipedia.org/wiki/Model_View_ViewModel

http://en.wikipedia.org/wiki/Model_View_Presenter

https://stackoverflow.com/questions/140098/is-mvc-ars-preferable-to-classic-mvc-to-prevent-overloading

And here a lot more:

http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)

Title: Is MVC now the only way to write PHP?


问:
When using MVVM, should you create new viewmodels, or swap out the models?
Say I have a viewmodel like this:

```<code>public class EmployeeViewModel
{
    private EmployeeModel _model;

    public Color BackgroundColor { get; set; }
    public Name
    {
        get { return _model.Name; }
        set
        {
            _model.Name = value;
            NotifyPropertyChanged(Name);
        }
    }
}
</code>```

So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view.

With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style?

I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.

答:
I think the question revolves around whether you are creating a new view or not.

If you have say multiple tabs, each one has an employeeView and corresponding viewmodel. when you open a new tab you instantiate a new view and viewmodel

If you have a single page, with 'next/prev employee' buttons then you probably have a single view and should stick with a single view model and change its properties.

If you switch out a viewmodel from a view you potentially muck up the bindings between the two. eg NotifyPropertyChanged as @konrad mentions

I've seen apps which create a new view each time which kind of works where you have a navigation controller or similar. But the more modern approach seems to be to have a single viewmodel tree for the app where its properties change overtime.

The multiple view approach can suffer from memory problems if you lose track of your views as you navigate around. Also if you are binding to a mediator or some other global events object you can find you are firing events on all your views when really you just want the active one to be triggered.


问:
TDD/BDD - Properly defining tests, adjusting tests, putting describe blocks inside it blocks
I am coming around with TDD/BDD.

I am a bit confused though, when it comes to initially writing my BDD tests and then adding more tests after the very broad tests.

For Example, lets say that I am giving requirements first:

It should take in an array.

It should print a list.

It should look for this specific condition.

I then write my tests:

```<code>describe('myApp', function (){
    it('should take in an array',function(){
        //expect
    });
    it('should print a list',function(){
        //expect
    });
    it('should look for this specific condition',function(){
        //expect
    });
});
</code>```

Now I need to add some functionality to my app to pass these tests, so say I write a function that checks to see if the app is actually passed an array. Or do I just check the input in the app itself? Example:

```<code>myApp(anArray) {
    checkArray(anArray) // returns true or false
}
</code>```

So now my app has a new method.. checkArray(). So I need to refactor my tests, but how do I modify them. Questions:

Do I write a new describe block?

Can/should i put a describe block inside an it block?

Should that be in my should be an array test?

```<code>describe('myApp', function (){
 it('should take in an array',function(){
    describe('myApp.checkArray, {
        it('should return true given an array', function(){
            //assertORexpectORwhatever
        });
    });
});
</code>```

});

OR should add the describe block after the first describe block like I always see, but then my initial SHOULD is no longer describing myApp. For example:

```<code>describe('myApp', function (){
    describe('myApp.checkArray, {

        //Describes myApp, not the checkArray function... *my problem*
        it('should take in an array',function(){

            it('should return true given an array', function(){
                //assertORexpectORwhatever
            })
        })
    });
});
</code>```

Am I doing something fundamentally wrong? Am i describing my problem well enough?

答:
The way you compose tests will tend to differ based on your own techniques and those of your team, but there are a couple of basics that would help in your situation:

In the first case where you're asking about the test it('should take in an array',...: I think the problem you're running into isn't a shortcoming of TDD/BDD, it's that this test is going to be difficult to positively prove in JavaScript (type checking with a flexible type system is hard). You're probably only going to be able to prove that your function rejects items that are not arrays or have array properties, which is likely to be good enough at any rate.

When you are looking to satisfy a test, you shouldn't typically add functions solely for the purpose of responding to your test suite; though in some cases it may actually be useful to add a function such as checkArray -- especially if you intend to throw an error if the check fails. Either way, your objects will need some way to communicate with the test suite - so add whatever functionality you need in order for it to do so; sometimes this is as simple as returning the correct results from your method calls.

There aren't any hard/fast rules for what should be inside of which kind of block -- when I'm using a test framework with describe/it grammar I use describe blocks to group functionality I think is part of a related set of behaviors and might nest them under something like a describe block for my Entire App. My inner describe blocks might be scoped to all of the things in a specific module or file, it could be related to a particular step of the application's life-cycle (initialization, operation, termination, etc.), or it could even be just a single object/function within my program.

I'm not any kind of authority on testing or what exactly your files should look like (I mentioned it depends on you and your team earlier, right?), but here is what one of my jasmine test suites looks like and it works for me:

```<code>describe("myApp.ViewModel", function() {
    beforeEach(function() {
        //setup some stuff relevent to every test
        //maybe instantiate the object to test
        //setup spies and other mock objects - spying on getJSON maybe...
    })
    describe("the constructor", function() {
        it("should return a specific type of object", function() {});
        it("should be defined but internally uninitialized", function() {});
        it("should have specific methods defined on its prototype", function() {
            // maybe I would even do sub `it` calls here, but not really required
        });
    });
    describe("initAsync", function() {
        it("should initialize the ViewModel asynchronously", function() {});
        it("should throw an error when initialized with no endpoint", function() {});
        it("should load 3 records initialized with the `data.svc/mock1` endpoint", function() {});
        it("should load 0 records initialized with the `data.svc/mock2` endpoint", function() {});
        // ...
    });
    describe("submitAsync", function() {
        // ...
    });
});
describe("myApp.Utils", function() {
    // ...
});
</code>```

You can imagine the entire code set above grouped inside of a describe("myApp", ...) block, if that made things easier to work with.

Body:
The way you compose tests will tend to differ based on your own techniques and those of your team, but there are a couple of basics that would help in your situation:

In the first case where you're asking about the test it('should take in an array',...: I think the problem you're running into isn't a shortcoming of TDD/BDD, it's that this test is going to be difficult to positively prove in JavaScript (type checking with a flexible type system is hard). You're probably only going to be able to prove that your function rejects items that are not arrays or have array properties, which is likely to be good enough at any rate.

When you are looking to satisfy a test, you shouldn't typically add functions solely for the purpose of responding to your test suite; though in some cases it may actually be useful to add a function such as checkArray -- especially if you intend to throw an error if the check fails. Either way, your objects will need some way to communicate with the test suite - so add whatever functionality you need in order for it to do so; sometimes this is as simple as returning the correct results from your method calls.

There aren't any hard/fast rules for what should be inside of which kind of block -- when I'm using a test framework with describe/it grammar I use describe blocks to group functionality I think is part of a related set of behaviors and might nest them under something like a describe block for my Entire App. My inner describe blocks might be scoped to all of the things in a specific module or file, it could be related to a particular step of the application's life-cycle (initialization, operation, termination, etc.), or it could even be just a single object/function within my program.

I'm not any kind of authority on testing or what exactly your files should look like (I mentioned it depends on you and your team earlier, right?), but here is what one of my jasmine test suites looks like and it works for me:

describe("myApp.ViewModel", function() {
    beforeEach(function() {
        //setup some stuff relevent to every test
        //maybe instantiate the object to test
        //setup spies and other mock objects - spying on getJSON maybe...
    })
    describe("the constructor", function() {
        it("should return a specific type of object", function() {});
        it("should be defined but internally uninitialized", function() {});
        it("should have specific methods defined on its prototype", function() {
            // maybe I would even do sub `it` calls here, but not really required
        });
    });
    describe("initAsync", function() {
        it("should initialize the ViewModel asynchronously", function() {});
        it("should throw an error when initialized with no endpoint", function() {});
        it("should load 3 records initialized with the `data.svc/mock1` endpoint", function() {});
        it("should load 0 records initialized with the `data.svc/mock2` endpoint", function() {});
        // ...
    });
    describe("submitAsync", function() {
        // ...
    });
});
describe("myApp.Utils", function() {
    // ...
});

You can imagine the entire code set above grouped inside of a describe("myApp", ...) block, if that made things easier to work with.


问:
Designing around shallow constness with inheritance

Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.

答:
Is there some other better solution that I have overlooked

An Image "is a"  ConstImage in the sense that it can always be "treated as const". Using inheritance strictly to model "IS A" relationships is also known as "Liskov substitution principle" (LSP), which is about behaviour. The LSP is fulfilled when an inherited class can always substitute its base class without violating the correctness of the program. And as long as you do not call a non-const method of an Image (which you typically won't do when passing it through a ConstImage reference), an Image will always behave like a ConstImage.


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I done so much...

Here is my current approach for situations when there is "something working", and you need to make it "work in some other way".

Get goals, that system should solve (if they not written) - write it. Ask manager, other employees, even former if they available. Ask customer or search any piece of documentation.

Get specificatio. If it not exist - write it. It is not worth to ask someone for it, as if it is not exist, then you are in situation when other don't care much. So only way to write own (later it will be much easier refer to it).

Get design. Not exist - write it. Try to refer to any documents and source code as much as possible.

Write detailed design to part that you need to change.

Define how you test it. So you could be sure that old and new code work in same way.

make system be able to be build in one step. And test with old code. Put it to SVC if it is not already.

Implement changes. Not earlier.

verify after a month or so, that nothing is broken.

One more optional todo that may require between each step: f off manager (project owner) who tell you that "these changes should be done already yesterday". After few projects, he may even start helping to get specs and docs in advance.

But usually (especially for scripts) it just not possible in business scope (cost will be too high, while value will be to low). One option is not to do any changes, until critical mass reached, and system goes off from production (e.g. new system will come) or management decided that all these is worth to do.

PS: I remember one code that were used for 5 clients with different settings. And each change (new feature) were required thinking of "what parts are used", and "what configuration clients have" so not to brake anything, and not to copypaste code. Putting their settings to project cvs, and writing specs, reduces this thinking time almost to 0.

Title: How do you dive into large code bases?