问:
Which version management design methodology to be used in a Dependent System nodes?
This is my first question so please indicate if my question is too vague and not understandable. My question is more related to High Level Design. We have a system (specifically an ATCA Chassis) configured in a Star Topology, having Master Node (MN) and other sub-ordinate nodes(SN). All nodes are connected via Ethernet and shall run on Linux OS with other proprietary applications.

I have to build a recovery Framework Design so that any software entity, whether its Linux, Ramdisk or application can be rollback to previous good versions if something bad happens.

Thus I think of maintaining a State Version Matrix over MN, where each State(1,2....n) represents Good Kernel, Ramdisk and application versions for each SN. It may happen that one SN version can dependent on other SN's version.
Please see following diagram:-

So I am in dilemma whether to use Package Management Methodology used by Debian Distributions (Like Ubuntu) or GIT repository methodology; in order to do a Rollback to previous good versions on either one SN or on all the dependent SNs. The method should also be easier for upgrading SNs along with MNs.

Some of the features which I am trying to achieve:-

1) Upgrade of even single software entity is achievable without hindering others.

2) Dependency checks must be done before applying rollback or upgrade on each of the SN

3) User Prompt should be given in case dependency fails.If User still go for rollback, all the SNs should get notification to rollback there own releases (if required).

4) The binaries should be distributed on SNs accordingly so that recovery process is faster; rather fetching every time from MN.

5) Release Patches from developer for bug fixes, feature enhancement can be applied on running system.

6) Each version can be easily tracked and distinguishable.

Thanks

答:
Imo, you want Puppet or a similar configuration management tool to satisfy req 1, 3 and 5. You can even manage puppet config in a git repo to satisfy req 6. It also sounds to me that using Debian packages would be better than git repos in your case for the following reasons:

dependency checks are integrated into dpkg (req 2)

apt-get caches binaries locally (req 4)

Of course, all of these can be reimplemented without reusing a configuration management tool and a package manager, but this sounds like more work. Finally, remember that no configuration tool is ideal, and the following issues may still arise:

an upgrade of some software entity breaks the configuration tool itself

a new version of software entity changes configuration in a backwards-incompatible way, e.g. by updating a database scheme and a rollback becomes problematic

common package managers such as APT may produce surprising behaviour (example)

Hence, it is still important to define your changes properly (scope, time window etc.) and roll them out in stages.


问:
How can I hide my signature in a program?
We have a university programming course and fellow students are asking some programming questions in our Facebook group. I'm a little hesitant to share all of my programs, especially if it's something cool for one of the assignments, since these are looked at by the TAs and they might notice if somebody has the same program and start asking questions on where it came from. Still, sometimes I'd like to share my code to help others, but I don't wanting people just grabbing my work.(Clarification: We are allowed to collaborate with the tasks) This is of course a thin line. While I want to help some people, I'm concerned that they may not have the academic honesty to rewrite the code on their own.

Most of my fellow students are not very advanced in their skills, so I'd get away with say hiding my name in Base-64 encoded string crafted into a discrete place. Still, it may be too obvious for a random string to be sitting around.

What options exist to hide my name in a program without it looking suspicious?

I've seen over at CodeGolf that they have made ascii art turn into other things when evaluated. Are there similar strategies I could utilize? The ideal solution would be something that looks like something that fits in discreetly but in reality has a function to prove that I coded it from the beginning.

Clarification: (Sorry, should have said this earlier) We're allowed to collaborate but have to explain our programs to the TAs to get the points. It's just for satisfaction to hide some Easter Eggs in other's code if it leaks out, especially since it may be tempting to exchange programs to check that the answers to problems they generate are equivalent etc or to see how others solve the problem.

答:
duozmo's suggestion of noops will possibly generate poor marks for sloppiness, but that might be a good thing to include in example code which is not supposed to be used verbatim.

That inspired me to think of an alternating signature pattern of tabs and spaces in both leading and trailing whitespace.

ContentLicense: CC BY-SA 3.0


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

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

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

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

答:
First of all, I assume this code is some kind of an API, because otherwise you would have known if there exist two classes that do want to use different implementations.

So, if you want a more coarse-grained API, go for the first alternative. If you want to let a programmer select implementation himself, go for the second alternative. Finally, if you want both, see the "robot legs" question in the Guice FAQ.


答:
Given that the problem is to hide a signature in source code where

it will not be immediately obvious

it cannot be removed casually or accidentally

it can be recovered found when needed, to a level of certainty that would constitute proof.

An interesting variation on Steganography.

You can't use formatting or whitespace, because that can be trivially removed by any competent IDE.

That really leaves only naming of variables and functions. You can't use a common distinctive substring, because it's too easily removed by a search and replace. That leaves the use of distinctive and original variable names that would be have to be removed individually. Spelling errors and foreign language words are good candidates.

```<code>if (a== x) {}   // disappears on reformatting
int gghhjj_i;   // easily removed by search and replace, if all the same
int couunt = 0;  //spelling
int nummer = 0; // german
float doppel = 0.0; // german
string spago = "xx"; // italian
boolean manana = true; // spanish
struct perzon;  // excess use of z's.
class employeej; // what if every variable contained a 'j'?
</code>```

The opportunities for creativity are boundless!

Then some simple text processing to extract and compare tokens will rapidly discover the plagiarists.

Title: How can I hide my signature in a program?

Body:
We have a university programming course and fellow students are asking some programming questions in our Facebook group. I'm a little hesitant to share all of my programs, especially if it's something cool for one of the assignments, since these are looked at by the TAs and they might notice if somebody has the same program and start asking questions on where it came from. Still, sometimes I'd like to share my code to help others, but I don't wanting people just grabbing my work.(Clarification: We are allowed to collaborate with the tasks) This is of course a thin line. While I want to help some people, I'm concerned that they may not have the academic honesty to rewrite the code on their own.

Most of my fellow students are not very advanced in their skills, so I'd get away with say hiding my name in Base-64 encoded string crafted into a discrete place. Still, it may be too obvious for a random string to be sitting around.

What options exist to hide my name in a program without it looking suspicious?

I've seen over at CodeGolf that they have made ascii art turn into other things when evaluated. Are there similar strategies I could utilize? The ideal solution would be something that looks like something that fits in discreetly but in reality has a function to prove that I coded it from the beginning.

Clarification: (Sorry, should have said this earlier) We're allowed to collaborate but have to explain our programs to the TAs to get the points. It's just for satisfaction to hide some Easter Eggs in other's code if it leaks out, especially since it may be tempting to exchange programs to check that the answers to problems they generate are equivalent etc or to see how others solve the problem.

Body:
Given that the problem is to hide a signature in source code where

it will not be immediately obvious

it cannot be removed casually or accidentally

it can be recovered found when needed, to a level of certainty that would constitute proof.

An interesting variation on Steganography.

You can't use formatting or whitespace, because that can be trivially removed by any competent IDE.

That really leaves only naming of variables and functions. You can't use a common distinctive substring, because it's too easily removed by a search and replace. That leaves the use of distinctive and original variable names that would be have to be removed individually. Spelling errors and foreign language words are good candidates.

if (a== x) {}   // disappears on reformatting
int gghhjj_i;   // easily removed by search and replace, if all the same
int couunt = 0;  //spelling
int nummer = 0; // german
float doppel = 0.0; // german
string spago = "xx"; // italian
boolean manana = true; // spanish
struct perzon;  // excess use of z's.
class employeej; // what if every variable contained a 'j'?

The opportunities for creativity are boundless!

Then some simple text processing to extract and compare tokens will rapidly discover the plagiarists.


问:
Can the possibility of a data race be ignored in some cases? (while having concurrent threads)
I am programming a game engine as a hobby project, and I would like to separate physics and drawing into two separate threads. The position vectors of entities are subject to modifications by the physics thread, while the drawing thread only requires read access. In pseudocode:

Physics thread:
    loop
        ...
        read entity position
        compute new position for entity
        write entity position
        ...
     end

Drawing thread:
    loop
        ...
        read entity position
        render entity
        ...
    end
```

Separating the drawing and physics into two threads allows for the decoupling of the  physics update rate from the drawing framerate. This enables things like easy slow motion effects and variable frame rates, but also makes it possible for the physics thread to modify a position vector at the exact same time as the drawing thread is reading the same value.

I hope I could get away without using mutexes, locks or other concurrency controls for the position vectors. The validity of the position data is not critical, and small errors resulting from non-atomic access are tolerable. My experience with concurrent programming is however fairly limited, and I fear that there are other issues stemming from asynchronous access that I am not aware of. What are the drawbacks of this approach? What alternatives are there?

I am programming in C++11 (using std::thread), on a multi-core x86 PC.

答:
The suggested architecture does feature a data race. Whether this is negligible depends on the specifics of the game and on the details of the implementation. As the rendering thread can access the shared state at any time, this state must always be in a consistent, valid state.

For example, let's consider what might happen if the physics thread moves an object. If it first updates the x coordinate, then y and z, then between or during those updates the render thread may access the position. If our object is moved from (0, 0, 0) to (1, 1, 1), then the render thread might for example see the intermediate value (1, 0, 0). This is absolutely not a problem if for one frame the object appears two pixels to the left. But if your game features fast-moving objects or teleports across the map, then the result may be more noticeable.

How can this be avoided? The data must be updated atomically to provide a consistent view onto the state. For example:

The whole state is protected via a mutex. Either the physics thread has write access or the drawing thread has read access. As the physics thread always has read access, it can keep processing, and queue up a set of modifications to apply once it regains access. This is a suboptimal solution as the drawing thread may be locked out for a long time (compared with the intended frame rate).

The state of each game object is protected via a mutex. This makes it much less likely for the two threads to require access to the same object at the same time, but we now have to obtain many more locks which will also degrade performance. This solution can still feature smaller inconsistencies, such as two objects that seem to be intersecting on screen, but are actually only very close to each other, as at the time of drawing only one object has been updated.

The game state exists exclusively of pointers to various game objects. When an object has to be updated, first a copy of that object is created. Then, the changes are applied to the copy. Once the object is in a consistent state, the pointer to that object is atomically updated to point to the mutated copy. This solution can still feature minor inconsistencies, as with the previous solution. This could be implemented in terms of locks, but actually only an atomic update is required.


问:
Should data models know where / how they're stored?
I have some classes that represent, for the most part, data that's deserialized from XML. They also have some behavior in them, because I don't want to suffer from an anemic domain model. These domain objects don't have any XML specific code in them, but they do have properties that correspond exactly to the tags and attributes in the XML.

Many of these classes' behaviors rely on resources loaded from disk, like images. For that, some properties / xml attributes are relative file paths to these resources. Now my problems begin. The absolute path to be constructed for these resources is based on a separate dependency - the root of the "project". Here's what I'm struggling with:

Should my domain objects store the full absolute path to their resources? Or just the relative paths? If they held the absolute path, then the classes that load them - my XML readers - will have to take a dependency on the project root in order to build the full path for them. If not, I'll have to make yet another layer of classes to handle that. I already have 3 layers, I don't know if I can handle any more!

Should my domain objects store their own paths for where they are on disk? It makes sense for them to know where their dependencies are in relation to them, but to know their own location just feels wrong to me intuitively. This is sort of unrelated to the other part of the question, but I think if I go the wrong way on this it could bite me later.

答:
I didn't understand the "dependency on project root" part, but it sounds like you may want to preserve relative paths in java properties / xml attributes and introduce a java property that represents path to the project root and has no corresponding xml attribute. You can initialize this property either in the constructor or via a setter method after deserializing the model.

Assuming that path to the project root does not have to be the same as the path to a serialized model, I would rather not store the path to a serialized model in the model itself. This would preclude potentially persisting the model to a database or other storage type, which sounds wrong.

I don't think you need one more layer of abstraction to solve both of these issues. A path to serialized model and a project root can be provided in some kind of a model manager or a factory.

Finally, I think it is worth having data and methods to process it together unless you're writing an ORM library. However, it is important to keep only those methods which are directly meant for processing data and factor everything else out to other classes in order to avoid placing multiple responsibilities on your class.


问:
Does a vm implemented in garbage collected language need a garbage collector?
This is more of a theoretical question. If jvm is implemented in go which itself is a garbage collected language, then does that jvm need a separate garbage collector to be implemented for its own operation? </p>

答:
Yes, it does. The reason is that garbage collection can only reclaim inaccessible resources, but what is accessible depends on the level on which you view the system.

The host VM implements garbage collection to reclaim memory that the guest program used but has now released. In your case, the guest program is another VM, and its guests are application programs. When an application program uses and discards memory, it no longer has a handle to that memory, so it can never use the values stored in it again. That, however, is a condition that only the guest VM can check.

From the point of view of the host VM, all the memory that the guest VM has passed out to the application was first passed out by the host VM to the guest VM, and the guest VM still has a handle to that memory (it has to have a handle to it, otherwise it wouldn't even be possible for the guest VM to implement garbage collection). It follows that if the guest VM doesn't reclaim a block of memory, the host VM can't reclaim that memory either, resources will leak and you may eventually run out. In general, garbage collection or another form of resource reclaiming is necessary for every level of virtualization that involves a change of ownership of physical resources.


答:
No, it can rely on the host language's garbage collector. Of course it has to be careful not to reference memory that is logically unreachable (unreachable from the guest program and not needed for the VM). But that is not fundamentally different from avoiding "logical memory leaks" (holding onto memory you don't need any more) in any other program written in the host language.

An example is RPython. Although it is unusual in that the RPython garbage collectors are written in (a low-level, manually-memory-managing subset of) RPython, all other RPython code acts almost entirely like an ordinary garbage-collected language. A VM written in RPython represents all guest language objects (and almost all objects needed only for its internal purposes) as garbage-collected RPython objects, rather than implementing a second GC only for the guest language. For example, in PyPy there is the W_Root base class. Everything that's in any sense a Python object inherits from it, but memory management for it and its subclasses is left to the RPython-level garbage collectors.

Title: Does a vm implemented in garbage collected language need a garbage collector?

Body: This is more of a theoretical question. If jvm is implemented in go which itself is a garbage collected language, then does that jvm need a separate garbage collector to be implemented for its own operation? </p>


答:
TL;DR

No.

Longer version.

When you are talking about "data models" I assume that you mean domain objects. Because "model" is not an object or class. It is an application layer.

Back to the point.

No. The domain object should not know "where" it is being store or even "if" it is has been store anywhere at all. The responsibility of domain object is to represent the business rules, which apply to a specific part of domain model (as defined in this book).

Since my primary language is PHP, the example will be in it:

```<code>$user = new User;
$user->setId(42);

$mapper = new UserMapper($xmlFileHandler);
if ($mapper->fetch($user)) {
    $user->setName('Ford Prefect');
    $mapper->store($user);
}
</code>```

The persistence of domain objects should be handled by data mappers. And you can have multiple mappers acting on same domain object.

For example: when you are loading data for "current user" domain object, it can be populated by the information that is in user's session, data from cache and info from one or more SQL tables.

Title: Should data models know where / how they're stored?

Body:
I have some classes that represent, for the most part, data that's deserialized from XML. They also have some behavior in them, because I don't want to suffer from an anemic domain model. These domain objects don't have any XML specific code in them, but they do have properties that correspond exactly to the tags and attributes in the XML.

Many of these classes' behaviors rely on resources loaded from disk, like images. For that, some properties / xml attributes are relative file paths to these resources. Now my problems begin. The absolute path to be constructed for these resources is based on a separate dependency - the root of the "project". Here's what I'm struggling with:

Should my domain objects store the full absolute path to their resources? Or just the relative paths? If they held the absolute path, then the classes that load them - my XML readers - will have to take a dependency on the project root in order to build the full path for them. If not, I'll have to make yet another layer of classes to handle that. I already have 3 layers, I don't know if I can handle any more!

Should my domain objects store their own paths for where they are on disk? It makes sense for them to know where their dependencies are in relation to them, but to know their own location just feels wrong to me intuitively. This is sort of unrelated to the other part of the question, but I think if I go the wrong way on this it could bite me later.

Body:
TL;DR

No.

Longer version.

When you are talking about "data models" I assume that you mean domain objects. Because "model" is not an object or class. It is an application layer.

Back to the point.

No. The domain object should not know "where" it is being store or even "if" it is has been store anywhere at all. The responsibility of domain object is to represent the business rules, which apply to a specific part of domain model (as defined in this book).

Since my primary language is PHP, the example will be in it:

$user = new User;
$user->setId(42);

$mapper = new UserMapper($xmlFileHandler);
if ($mapper->fetch($user)) {
    $user->setName('Ford Prefect');
    $mapper->store($user);
}

The persistence of domain objects should be handled by data mappers. And you can have multiple mappers acting on same domain object.

For example: when you are loading data for "current user" domain object, it can be populated by the information that is in user's session, data from cache and info from one or more SQL tables.


问:
Why std::allocators are not that popular?
With the latest trends about C and C++ applications, and with latest I mean the latest years, I was expecting to see std::allocators to be used way more frequently than what it really is.

Modern applications are usually multithreaded or with form of concurrency in them, and they manage a significant amount of memory, especially in some fields like games and multimedia applications; so the usual high cost of the allocation/deallocations rises and impacts the performances even more than in old applications.

But for what I can see this kind of memory management through std::allocators is not popular, I can't even count 1 library that I know of, that is using any rationale about a standardize way of managing memory.

There is a real reason why std::allocator is not popular ? Technical reasons ?

答:
An allocator is a dependency-injected policy, into the standard containers. It is there mostly to allow client code to separate allocation policy from instantiation, in already implemented containers.

The problem appears when you need to use std:: containers, and the default allocation policy (as implemented by std::allocator) doesn't suit the needs of your project (e.g. you want the std::vector implementation to throw if more than 1024 objects are allocated, you want to use a memory pool, or ensure the allocations are all preallocated in a certain memory area and so on).

If you could not inject a different allocator into the containers, this would prohibit you from using the std::containers alltogether in some projects.

To get around this (and ensure you can still use the std:: containers when you have complex memory requirements), the allocator is a templated parameter for the containers.

To answer your question: most people don't use std::allocators because when they write client code they have full control of the allocations - so they don't need to inject an allocation policy - and when they use library code, the std::allocator is usually enough.


问:
Why does TDD work?
Test-driven development (TDD) is big these days. I often see it recommended as a solution for a wide range of problems here in Programmers SE and other venues. I wonder why it works.

From an engineering point of view, it puzzles me for two reasons:

The "write test + refactor till pass" approach looks incredibly anti-engineering. If civil engineers used that approach for bridge construction, or car designers for their cars, for example, they would be reshaping their bridges or cars at very high cost, and the result would be a patched-up mess with no well thought-out architecture. The "refactor till pass" guideline is often taken as a mandate to forget architectural design and do whatever is necessary to comply with the test; in other words, the test, rather than the user, sets the requirement. In this situation, how can we guarantee good "ilities" in the outcomes, i.e. a final result that is not only correct but also extensible, robust, easy to use, reliable, safe, secure, etc.? This is what architecture usually does.

Testing cannot guarantee that a system works; it can only show that it doesn't. In other words, testing may show you that a system contains defects if it fails a test, but a system that passes all tests is not safer than a system that fails them. Test coverage, test quality and other factors are crucial here. The false safe feelings that an "all green" outcomes produces to many people has been reported in civil and aerospace industries as extremely dangerous, because it may be interepreted as "the system is fine", when it really means "the system is as good as our testing strategy". Often, the testing strategy is not checked. Or, who tests the tests?

In summary, I am more concerned about the "driven" bit in TDD than about the "test" bit. Testing is perfectly OK; what I don't get is driving the design by doing it.

I would like to see answers containing reasons why TDD in software engineering is a good practice, and why the issues that I have explained above are not relevant (or not relevant enough) in the case of software. Thank you.

答:
Software is organic, when structural engineering is concrete.

When you build your bridge, it'll remain a bridge and it's unlikely that it will evolve into something else within a short period of time. Improvements will be made over months and years, but not hours and days like in software.

When you test in isolation, there are normally two types of frameworks you can use. Constrained framework and unconstrained. Unconstrained frameworks (in .NET) allow you to test and substitute everything, regardless of access modifiers. I.e. you can stub and mock private and protected components.

Most of the projects that I have seen use constrained frameworks (RhinoMocks, NSubstitute, Moq). When you test with these frameworks, you have to design your application in such a way that you can inject and substitute dependencies at runtime. This implies that you must have a loosely coupled design. Loosely coupled design (when done right) implies a better separation of concerns, which is a good thing.

To summarise, I believe that thinking behind this, is that if your design is testable, therefore it's loosely coupled and it has a good separation of concerns.

On a side note, I've seen applications that were really testable, but poorly written from object oriented design perspective.

Title: Why does TDD work?


答:
The popularity of a language or a library concept is in an inverse correlation with its underlying complexity.

The std::allocator is a low level concept and as such has potential pitfalls. Having a custom allocator upfront is likely to be judged a premature optimisation. Further, similarly to other low level concepts, it is generally preferred to delegate the work allocation management to libraries (stdlib, boost) unless the overhead of handling the complexity of your own allocations is absolutely warranted.

Consider pointers as just one supporting example of this thesis. We love pointers for their unfetterred access to memory and zero overhead, but in C++ we know better to use scoped/raii wrappers to manage the complexity, that is until we explicitly need the performance or can all agree on some non-owning semantics for certain well-defined use-cases.

When using an std::allocator you need to consider the ABI and the API compatibilities, and wonderful question such as the desired behaviour when the code is engaging
std::vector<T,A1>().swap(std::vector<T,A2>()) with different (and stateful!) A1 and A2 allocators. Further, some containers don't even use the allocator in the way you intended! Take a look at std::list<T,A> or std::map<K,T,C,A> for example. The natural expectation is for the allocator to be used to allocate objects of type T for a list or a pair<const K,T> for a map, however in practice a standard library implementation will asks to allocate a list or map node, and even the size of the node can be different between release and debug builds. Custom allocators are rife with minutia, and the added complexity and detail is unnecessary for the most common programming tasks.

Title: Why std::allocators are not that popular?

Body:
With the latest trends about C and C++ applications, and with latest I mean the latest years, I was expecting to see std::allocators to be used way more frequently than what it really is.

Modern applications are usually multithreaded or with form of concurrency in them, and they manage a significant amount of memory, especially in some fields like games and multimedia applications; so the usual high cost of the allocation/deallocations rises and impacts the performances even more than in old applications.

But for what I can see this kind of memory management through std::allocators is not popular, I can't even count 1 library that I know of, that is using any rationale about a standardize way of managing memory.

There is a real reason why std::allocator is not popular ? Technical reasons ?


问:
Embedding XACML PDP?
I need to implement a flexible Access Control system for a framework used by a couple of .NET applications.

I have looked into Attribute-Based Access Control (ABAC) and XACML and this seems to provide the necessary flexibility to make decisions not only based on the user identity, but also on information about the requested resource.

Typicial scenario where I need this:

Allow access to patient files only to doctors who are assigned to the patient.

However externalizing the authorization to a third party provider or another PDP server because would mean a network call every time the PEP (the application) performs an action that has to be authorized.

Does it make sense to use XACML with an embedded PDP? I.e. the application transforms authorization decisions to XACML requests, then calls an embedded PDP module with the request which resolves it, queries the DB for resource and policy information and generates a XACML response.

Or is XACML only useful in distributed Access Control scenarios? Is it generally more useful to implement a custom access control system if I don't plan to externalize the decision making point?

答:
Yes, it makes sense to embed the PDP.

XACML is more about:

a standardized policy language

a standardized request / response scheme

and a standardized conceptual architecture with the notion of PEP or PDP.

It doesn't mean the PDP cannot be embedded. What matters is that you define and manage your policies centrally but you can always distribute them to embedded PDPs or service PDPs. You could even have a mix of embedded / service PDPs.

I work for Axiomatics - a XACML vendor - and we see many customers using embedded PDPs either for performance reasons but usually more for a lifecycle reason (i.e. the customer doesn't want to have to set up and maintain a separate server).

There are 2 possible drawbacks to embedding a PDP:

if you want to update the PDP library, you'll have to to do that everywhere it's been embedded.

if you want to use policy information points (PIP), you have to configure each PIP individually at each embedded PDP if at all possible.

Title: Embedding XACML PDP?


问:
What does it mean when data is scalar?
I don't know what scalar means exactly, but I'm trying to see if I'm thinking about it correctly. Does scalar relate to arbitrariness where the type of data could be any type, or a system is not able to know what the data is in advance. </p>

答:
A supplemental mnemonic, to Karl Bielefeldt's great answer:

A simple way of thinking about it, is "can this be on a scale?"

An integer can be on a scale.

A fixed-size integer can be on a scale, e.g. from -2147483648 to 2147483647.

A real number can be on a scale.

A character, boolean, or fixed-precision decimal can all be on a scale. Even a string can be on a scale (we use such in sorting).

Hence "scalar".

A database row cannot be on a scale. A complex number cannot be on a scale. An object representing an email message cannot be on a scale. An array, vector or matrix cannot be on a scale.

Title: What does it mean when data is scalar?


问:
Word recognition in a string without spaces or punctuation marks
I have a small C# project that reads a file and gives me an output: a string that does not contain spaces nor any types of punctuation marks. It may also contain a few misspellings.

Ex.
Output:
 THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG

I wonder if there is a way to analyze this string by using text mining/data mining and/or regular expressions to indentify the words (preferably nounds, verbs and so forth.) in the string?

I want to read a bunch of files giving me different outputs and put them in statistical order from the one with the most found words to the one which only contain a string of mumbo jumbo.

Also, if the string contain misspellings like:

THEQUICGBROWNFOSJUMPSOVERTHHLAZYDOG

I know that regular expression can calculate the "distans" from a misspelled word and find the most matching one (using a corpus and probability) but this might prove more of a challenge as the string does not have any spaces or punctuation marks.
Any ideas how I can solve this?

答:
Thanks to amon I managed to get the algorithm going!

By using this here code a Trie was implemented and filled with the english dictionary (around 23600 words).

By starting reading from each index in the string, feeding it the next char and then the next until the trie does no longer find any more possible solutions (misspelled word or ending of a real one plus the start of the next), judging this outcome and increase the index by 1 words can be found and analyzed.

V

THEQUICKBROWNFOX... Finds THE

_V

THEQUICKBROWNFOX... Finds HE

__V

THEQUICKBROWNFOX... Finds EQ

and so forth.

In this sequence it is possible to check the weigted edit distance between words and find misspellings. However, due to a lack of time this was never fully implemented in my project.

My project has a more advanced approach to this as it is a statistics tool to run sevreal iterations on a given set of texts so feel free to ask if you have more specific questions and I will answer by the best of my capabilities.

Thank you for all the help in this!


答:
Something similar I've used before is to create variables named the same as other important variables but leet their names depending on the text editor so the change is not easily obvious, or use letters with accents.
Call several functions, to which you send many of the program's important variables from an if statement, utilising your variables, which will never be true, eg if( 1eft == wrōng)
Set some important variable in a useless function to your obfuscated signature.

You should be able to find several tutorials on 'How to write unmaintainable code' which could help.


问:
How to get around the Circular Reference issue with JSON and Entity
I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON.

I am using the code first method to create my database.  When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)

```<code>class parent
{
   public List<child> Children{get;set;}
   public int Id{get;set;}

}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId")]
    public parent MyParent{get;set;}
    public string name{get;set;}
 }
</code>```

When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent.

I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point.

I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).

```<code>Base.baseParent basep = (Base.baseParent)parent;
return Json(basep, JsonRequestBehavior.AllowGet);
</code>```

The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name).  This method seems forced although it works.

NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model.  In my searching I have not seen a good method to overcome this problem.

My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data.  While maintaining a consistant model across layers (or as best as I can come up with).

答:
A simpler alternative to attempting to serialize the objects would be to disable the serialization of parent/child objects. Instead, you could make a separate call to fetch the associated parent/child objects as and when you need them. This may not be ideal for your application, but it's an option.

To do this, you could set up a DataContractSerializer and set the DataContractSerializer.PreserveObjectReferences property to 'false' in the constructor of your data model class. This specifies that the object references should not be preserved on serializing the HTTP responses.

Examples:

Json format:

```<code>var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
    Newtonsoft.Json.PreserveReferencesHandling.None;
</code>```

XML format:

```<code>var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
var dcs = new DataContractSerializer(typeof(Employee), null, int.MaxValue,
    false, /* preserveObjectReferences: */ false, null);
xml.SetSerializer<Employee>(dcs);
</code>```

This means that if you fetch an item which has child objects referenced, the child objects won't be serialized.

See also the DataContractsSerializer class.

Body:
A simpler alternative to attempting to serialize the objects would be to disable the serialization of parent/child objects. Instead, you could make a separate call to fetch the associated parent/child objects as and when you need them. This may not be ideal for your application, but it's an option.

To do this, you could set up a DataContractSerializer and set the DataContractSerializer.PreserveObjectReferences property to 'false' in the constructor of your data model class. This specifies that the object references should not be preserved on serializing the HTTP responses.

Examples:

Json format:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
    Newtonsoft.Json.PreserveReferencesHandling.None;

XML format:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
var dcs = new DataContractSerializer(typeof(Employee), null, int.MaxValue,
    false, /* preserveObjectReferences: */ false, null);
xml.SetSerializer<Employee>(dcs);

This means that if you fetch an item which has child objects referenced, the child objects won't be serialized.

See also the DataContractsSerializer class.


答:
@teresko gave you already a good answer for your question 2, and I try to add an answer for part 1:

Lets say you have a business object Image with some properties, including a (persistent) property FilePath (I assume the Image object not to load that data into memory automatically, just beeing a reference to the data or containing meta data about the image file). Obviously, since you have several images to deal with, each one having its data under the same project root folder (and this folder  may change in the future), you don't want to store the absolute path in each image object, only relative paths. Lets assume further you have a business object Project with a property RootFolder. This business object may be a persistent object, too, or it may be created and initialized at run time, whatever fits best to your requirements.

Now you have two options for accessing the image files:

either you add a (derived) property AbsoluteFilePath to your Image class. To make this property return the concatenation of the relative path and the root folder, your Image objects needs depend on the Project object. This dependency might be constructed / injected during the construction process of the Image object, or you have a two-phase construction process where after the deserialization the dependency is injected afterwards, or it may be hardcoded somehow in your Image object, but you cannot avoid it

or, you don't add such a property to the Image class, and let the client code (the code using the Image object) handle the problem. For this case, it may be helpful to add a helper method GetAbsolutePath(relativePath) to the Project class and reuse this method throughout your code. This has the advantage that you avoid the dependency between Image and Project above, but the drawback that the client code gets a little bit more lengthy: for example, instead of

```<code>  ReadFile(image.AbsoluteFilePath)
</code>```

you will have to write

```<code>   ReadFile(project.GetAbsolutePath(image.FilePath))
</code>```

You will have to make a decision between those two options, and from the information you gave in your question, it is impossible for me to tell which is the better one in your case - both options are sometimes reasonable. But IMHO none of these two options leaves you with an "additional layer" or an "anemic domain model".

Body:
@teresko gave you already a good answer for your question 2, and I try to add an answer for part 1:

Lets say you have a business object Image with some properties, including a (persistent) property FilePath (I assume the Image object not to load that data into memory automatically, just beeing a reference to the data or containing meta data about the image file). Obviously, since you have several images to deal with, each one having its data under the same project root folder (and this folder  may change in the future), you don't want to store the absolute path in each image object, only relative paths. Lets assume further you have a business object Project with a property RootFolder. This business object may be a persistent object, too, or it may be created and initialized at run time, whatever fits best to your requirements.

Now you have two options for accessing the image files:

either you add a (derived) property AbsoluteFilePath to your Image class. To make this property return the concatenation of the relative path and the root folder, your Image objects needs depend on the Project object. This dependency might be constructed / injected during the construction process of the Image object, or you have a two-phase construction process where after the deserialization the dependency is injected afterwards, or it may be hardcoded somehow in your Image object, but you cannot avoid it

or, you don't add such a property to the Image class, and let the client code (the code using the Image object) handle the problem. For this case, it may be helpful to add a helper method GetAbsolutePath(relativePath) to the Project class and reuse this method throughout your code. This has the advantage that you avoid the dependency between Image and Project above, but the drawback that the client code gets a little bit more lengthy: for example, instead of

  ReadFile(image.AbsoluteFilePath)

you will have to write

   ReadFile(project.GetAbsolutePath(image.FilePath))

You will have to make a decision between those two options, and from the information you gave in your question, it is impossible for me to tell which is the better one in your case - both options are sometimes reasonable. But IMHO none of these two options leaves you with an "additional layer" or an "anemic domain model".


问:
Practical use of generic inheritance and interactions with non-generics?
I've been trying to learn more about generics, and I finally felt that I ran into a situation that it would be more useful to use it instead of only regular classes. Would the following be a practical use of generics?

A spaceship has hardpoints that can equip only certain types of equipment. The equip function has code to determine if the hardpoint can equip an equipment item based on what the generic parameter T is assigned to.

```<code>class Equipment {
...
}

class Thruster : Equipment {
...
}

class Spaceship {
    void Equip<T>(Hardpoint<T> hardpoint, Equipment equipment) {
        hardpoint.Equip(equipment);
    }
}

class Hardpoint<T> where T : Equipment {
    void Equip(Equipment equipment) {
        ...(check if equipment inherits from or is of type T)
    }

    ... (some other code common to all hardpoints)
}

class ThrusterHardpoint : Hardpoint<Thruster> {
    .... (some code specific to thruster hardpoints)
}
</code>```

答:
I don't like this bit:

```<code>void Equip(Equipment equipment) {
    ...(check if equipment inherits from or is of type T)
}
</code>```

And that's the same thing @MikeSW apparently meant, but didn't elaborate and got downvoted.

If you have generics (reified at that, in C#), why do you leave type-checking until runtime?

The equip function has code to determine if the hardpoint can equip an
  equipment item

...or you are manually doing the job the type system should be doing for you and you're giving up compile-time type safety. With what good purpose? What justifies that design choice?

Body:
I don't like this bit:

void Equip(Equipment equipment) {
    ...(check if equipment inherits from or is of type T)
}

And that's the same thing @MikeSW apparently meant, but didn't elaborate and got downvoted.

If you have generics (reified at that, in C#), why do you leave type-checking until runtime?

The equip function has code to determine if the hardpoint can equip an
  equipment item

...or you are manually doing the job the type system should be doing for you and you're giving up compile-time type safety. With what good purpose? What justifies that design choice?


问:
comparison of floating point numbers vs. comparsion of Integers in C
Does comparison of floating point numbers takes (considerably) longer time than comparison of Integers in C?

I just wrote a C program of heap sort to sort floating point numbers.

I am on ubuntu 14.04 and I used time command to check the time taken by this program for sorting 50, 5000 and 50000 random numbers and then I just changed all double to int and again checked time for 50, 5000 and 5000 numbers and statistics are as follows:

```<code>$ time ./heap 50 < input.txt

real    0m0.003s
user    0m0.001s
sys 0m0.002s
$ time ./temp 50 < input.txt

real    0m0.003s
user    0m0.001s
sys 0m0.002s
$ time ./heap 5000 < input.txt

real    0m0.008s
user    0m0.007s
sys 0m0.002s
$ time ./temp 5000 < input.txt

real    0m0.005s
user    0m0.004s
sys 0m0.001s
$ time ./heap 50000 < input.txt

real    0m0.030s
user    0m0.028s
sys 0m0.002s
$ time ./temp 50000 < input.txt

real    0m0.027s
user    0m0.026s
sys 0m0.002s
$ time ./heap 500000 < input.txt

real    0m0.263s
user    0m0.259s
sys 0m0.003s
$ time ./temp 500000 < input.txt

real    0m0.219s
user    0m0.216s
sys 0m0.003s
</code>```

Here heap is the executable of floating point heapsort and temp is the executable of Integer number heapsort.

As we can see there is noticeable difference in running times? What is the reason? I can upload the codes if needed.

答:
Generally, we would expect that FP operations are more expensive. Not to talk about doubles. That is because floats demand high-complexity operations. They also demand special caring in mathematic functions. They are an approximation of the number you want. So these functions do what they can do to achieve small errors.

Floating point arithmetic is implemented by the FPU. On CPUs that are in personal computers, FPU is advanced comparing to CPUs of embedded systems and other mobile devices (smartphones etc). And that is because floating point arithmetic isn't as power efficient as integer arithmetic.

So the conclusion here, considering that you work on a personal computer and from seeing your time deltas, the results are logical. If you'd run this program on a smartphone you would see a bigger delta in times.


答:
Timing your code like this doesn't say much.

There is overhead of bash's text interpreter

There is overhead of the kernel's program loader

There is overhead of the process itself (initialization and dylib linking)

The data read from the file is included in the timing (atoi and/or atof)

Did you use a AlmostEqual2sComplement method or just the == operator?

More about AlmostEqual2sComplement

Even if you would use a more precise timing, which should be included in the program. I would say that the difference is even larger. When we use two floating points, f1 = 2.25 + 2.75 and f2 = 2.5 + 2.5. Now a comparison like fp1 == fp2 will probably return false. Here an article on how to compare floating points. That means that you can't use a fp1 == fp2 in your benchmark and the AlmostEqual2sComplement() function you're looking for needs so many more instructions for a better comparison that the actual comparison between floating points is much more slower than comparing two integers.

Even if you want to keep using fp1 == fp2 the best answer to your question would be that it totally depends on the processor and compiler. Just a data comparison you need to make sure that both data items are equally in bit length. So when a float is 64-bit you'll need a 64-bit integer too. Then the == comparison could be equally fast in theory but again it depends on compiler and processor.

Title: comparison of floating point numbers vs. comparsion of Integers in C

Body:
Does comparison of floating point numbers takes (considerably) longer time than comparison of Integers in C?

I just wrote a C program of heap sort to sort floating point numbers.

I am on ubuntu 14.04 and I used time command to check the time taken by this program for sorting 50, 5000 and 50000 random numbers and then I just changed all double to int and again checked time for 50, 5000 and 5000 numbers and statistics are as follows:

```<code>$ time ./heap 50 < input.txt

real    0m0.003s
user    0m0.001s
sys 0m0.002s
$ time ./temp 50 < input.txt

real    0m0.003s
user    0m0.001s
sys 0m0.002s
$ time ./heap 5000 < input.txt

real    0m0.008s
user    0m0.007s
sys 0m0.002s
$ time ./temp 5000 < input.txt

real    0m0.005s
user    0m0.004s
sys 0m0.001s
$ time ./heap 50000 < input.txt

real    0m0.030s
user    0m0.028s
sys 0m0.002s
$ time ./temp 50000 < input.txt

real    0m0.027s
user    0m0.026s
sys 0m0.002s
$ time ./heap 500000 < input.txt

real    0m0.263s
user    0m0.259s
sys 0m0.003s
$ time ./temp 500000 < input.txt

real    0m0.219s
user    0m0.216s
sys 0m0.003s
</code>```

Here heap is the executable of floating point heapsort and temp is the executable of Integer number heapsort.

As we can see there is noticeable difference in running times? What is the reason? I can upload the codes if needed.


问:
How to implement a hybrid role-based access control model?
I am writing an enterprise web-forms-frontend application for in-house use. It has Direct access control (DAC) masquerading as Role-based access control (RBAC).

For anonymization purposes, let's call the main unit of information stored in my application a Document, and the roles in the company a Boss, a Grunt and a C-level executive. There are also Externals (e.g. somebody working for a business partner of ours). The general guideline is that everybody but externals should be able to read all documents, C-level execs can write everything, Bosses can write the Documents belonging to their own department, and Grunts can only write Documents personally assigned to them. Fairly standard thus far.

But what users actually want is that they can make arbitrary exceptions to the above. They want that any person in the system can be granted write access to any Document, and that Externals can be granted Read access to any document. (Actually, it is more complicated than that, with more roles and finer granularity of permissions, including management of who can propagate which permission to others, but the above description illustrates the core of the problem well enough). So what I have is basically permissions on a personal level, and the roles are only a convenient way of having default settings for the personal-level permissions when a user or a Document is added to the system, instead of having somebody fill out a whole row or column in an access control matrix by hand.

Now I have already designed a Permissions table in my database, which has a User FK, Document FK and columns for the different types of permissions. What I am not sure is what I should save in the table.

Alternative 1: I save all permissions in this table (pure DAC) and have the logic tier mimic a RBAC. E.g. when a new Boss is added, a row for each Document in the system is added to the DB, with Read permissions for all documents and Write for the Documents of her department.

Alternative 2: I save the deviations from the role guidelines only. So when a new Boss is added, nothing is written to the permissions table. But when an executive gives a Boss the rights to write to a Document from a different department, then a single row is added to reflect that information.

I am not sure which alternative would be better. The first one feels closer to textbook implementation, and if a principle has made it into a textbook, then there is normally good reason to use it. But in my case, it also hurts the DRY principle - after all, if the information that a C-level exec can write to Document X is derivable from his role, writing a row with this information in the DB is redundant.

What are the advantages and disadvantages of each approach in terms of a) application performance and b) complexity of implementation? What headaches can I expect from each?

Keep in mind that 1) I don't plan to implement a full logic tier. The whole application is practically a convenient CRUD frontend to a database, so I will be doing DB queries for each page view instead of keeping a collection of Document objects in memory. (I know the advantages of a MVC pattern, but it was decided that it will be overkill for this project). 2) I am programming this in ASP .NET 4.5, so the closer I stay to roles, the more I can let the framework do the heavy lifting for me. 3) I have thought of implementing groups orthogonal to the roles to manage access, but it doesn't make sense in my case.

答:
You should not implement your own authorization model but rather use existing ones e.g. an RBAC implementation, claims-based access control, or attribute-based access control (ABAC).

With respect to ABAC, there is an authorization standard that exists which you can use to define your authorization policies. This standard is called XACML, the eXtensible Access Control Markup Language. You can read up on both topics here:

NIST's page on attribute-based access control (ABAC)

OASIS extensible access control markup language (XACML)

XACML defines an architecture with the notion of:

a policy decision point (PDP),

a policy enforcement point (PEP), and

a policy information point (PIP).

In the typical flow, the PEP protects your data / service / API. The PEP would send an authorization request to the PDP:

Can user Alice view record #123?

The PDP would turn to the PIP to retrieve missing attributes e.g. the user's role and clearance as well as resource attributes e.g. the sensitivity of data, a whitelist or blacklist... Based on the new information, the PDP can reach a decision: Permit or Deny. Access is allowed or blocked.

With XACML there is no limit to the richness of the authorization policies. I work for a company, Axiomatics, that implements XACML, and our solutions are used in manufacturing, healthcare, banking to secure access to sensitive data in a dynamic way (e.g. managers can edit documents that they own).

XACML enables externalized authorization that is managed centrally. It also enables what I like to call any-depth authorization meaning that you can apply XACML to web APIs, business logic, presentation UIs, as well as databases.

HTH


答:
Preventing plagiarism in NOT your job as a student, that's purely in the hands of an instructor / TA.

Generally speaking treat school like it were closed source business. Your fellow students are colleagues for other employers. You can not share code beyond simple one liners and such, and you NEVER share entire classes or projects.

Hiding "Easter Eggs" in code is generally viewed as unprofessional. (Opinions may vary here)

Don't make smelly code your signature

Your "signature" or how you differentiate your code from others should be tasteful, and not hinder your code "smell" in any manner. This is why I strongly discourage the following:

Intentionally misspelling things (variables, method names)

Intentionally adding code "oddities" like no-ops for the purposes of marking code as yours.

Using non-standard or unusual code structure (white space, line breaks, ect)

Using non-standard or unusual coding patterns (actual code logic)

Unnecessary obfuscation of code (burying methods with in methods without reason)

Any other sort of code trickery or wizardry to try and distinguish it in an unusual manner.

Then how do I protect my code?!

Generally speaking restricting availability is your best way to protect your code. If you don't make it public and no one hacks your computer your code is generally safe. Sure it could be decompiled, reverse engineered, etc. At that point it's not like it'll match the code that generated it anyways.

I want to make it public, but prevent it from being plagiarized

Just no... By all means messy wizardry in your code could make a plagiarist stand out assuming that they make their code available as well... and they won't.

It'll also make you look terrible when others look over your code and go. "what the hell is with all the typos and no-ops?"

But I want a code signature, something I can look at code and say I did this, it was me, this is mine

Honestly if you code well it should generally be indistinguishable from any other code in the projects you work on. Sure their might be nuances that let you know what you worked on versus what Bob did, but these should be fairly mild.

The only time code stands out in a big way among peers is if something is new and never been done before within your circle, or it smells in a way unique to your circle.


答:
At the CPU level, integer and floating point operations are separate instructions.

An integer is a simple bit pattern where each bit represents a power of two or a sign bit. There are many microcode optimizations in modern CPUs (even on mobile devices) that make integer arithmetic and comparisons super fast.

Floating point operations and comparisons are more complex. The vast majority of modern CPUs that can handle floating point use the IEEE-754 standard. A floating point number (or double, or long double, the idea is the same) is more complex: it has both a mantissa and an exponent in addition to the sign bit. It also has special bit patterns that represent NaN (not a number), positive and negative infinity, as well as positive and negative zero.

What this means in practice is that even if a floating point compare or add or whatever other operation is a single CPU instruction, that instruction has a lot of work to do and will take several times longer than an integer operation. What is the result of "NaN < 4.5" or "7.0 < 7.0"? What about "1e-30 < 1e30"? The CPU has to be able to deal with the special "numbers" such as NaN and treat them correctly according to the spec. It also has to be able to deal with overflow or underflow situations where two numbers cannot realistically be used together due to limitations in the size of the exponent.

The circuits in the CPU have to be able to handle all of this which adds complexity, adds time to floating point processing, and means the program you wrote to sort floats will take longer.

Another thing that might be worth looking into (but is not strictly part of this answer) is to offload the floating point program to a GPU. Graphics processors rival CPUs here in 2014 for complexity and circuit size. They are highly parallel and highly optimized for floating point operations, since 3D graphics rely so heavily on floating point math.

Writing a program to sort floats using the GPU might be an interesting diversion and a good learning experience.


问:
Dealing with similar objects with different method signatures
I am fairly new to OO design and have problems with the design of some software and looking for a pattern or a combination of patterns that could help me solving my problem.

I have a type that has a collection of different geometric shapes (say lines, rectangles, and cubes). I actually even have composites of these shapes.
Each shape has one or more values. A value is a coordinate (between one-dimensional for lines and three-dimensional for cubes).

All types of shapes have two methods that are essential. A method for adding values and a method for getting all values of a shape. E.g. Cube.AddValue(new Value3D{X=4,Y=7,Z=11}) or Line.AddValue(new Value1D{X=42}) respectively Cube.GetValues() would return a collection of Value3D and Line.GetValues() would return a collection of Value1D.

Since these methods have fundamentally different signatures, I can't just derive from a single interface to store all of these different objects in one collection. Splitting the collection into multiple separate collections, one for each type would be possible, but not desirable since they belong together (domain wise).

I've considered using three-dimensional values for all shapes and just ignoring Y/Z for lines/rectangles, but that isn't really nice and would actually violate the O and L in SOLID (a 4th dimension is possibly needed in the future).

Another possibility would probably be to use a generic Interface like IShape<T> where T is Value*D. This interface would look like:

```<code>public interface IShape<T> {
    public IEnumerable<T> GetValues();
    public void AddValue(T value);
}
</code>```

But this would require another, non-generic interface INonGenericShape {} because I can't use a generic interface without specifying the type. I would end up with something like this:

```<code>public class SomeShape{
    private IList<INonGenericShape> _shapes = new List<INonGenericShape>();
}
</code>```

But then I could as well use System.Object, since IShape does not provide any valuable information. So here I am, not knowing how to solve this (storing the objects in a single collection for consumers of that class). Can anyone provide some idea or insight?

答:
How about something like this:</p>

```<code>public interface ICoordinateValue {}

public class Value1D : ICoordinateValue {}
public class Value2D : ICoordinateValue {}
public class Value3D : ICoordinateValue {}

public interface IShape
{
    IEnumerable<ICoordinateValue> GetValues();
    void AddValue(ICoordinateValue value);
}
</code>```

Body:
How about something like this:

public interface ICoordinateValue {}

public class Value1D : ICoordinateValue {}
public class Value2D : ICoordinateValue {}
public class Value3D : ICoordinateValue {}

public interface IShape
{
    IEnumerable<ICoordinateValue> GetValues();
    void AddValue(ICoordinateValue value);
}


问:
Is converting/casting a boolean to int a good idea?
Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/interpreters.

So I came across this question:

How do I convert a boolean to int in Python? Can I just do int(mybool)?

My response was to write:

```<code>1 if mybool else 0
</code>```

My reasoning was that blindly "casting" to int would rely on the internal implementation of the compiler/interpreter. And who knows, if running through a different interpreter int(mybool) might return something else. Explicitly stating the value for a "truthy" value and for a "falsey" value will always yield the expected behaviour.

This is surely something which one can consider for most languages.

Am I too picky about this? I know that I have written int(mybool) myself in the past. And that question made me think: Was that okay? Given that this is a very common case, are the compilers/interpreters smart enough to to "the right thing" for bool -> int conversions?

Now, for the special case for duck-typing languages like Python, int(mybool) might certainly be a really bad idea, but other languages are a bit clearer on their typing.

答:
With other languages the situation is not so clear, but python happens to be specified in such a way that you can depend on it always casting to 1 and 0.  Python's designers are some of the best with regard to the principle of least astonishment.

The issue is that python is relatively rare as a first language, and programmers transfer practices from other languages that become superstitions in the new language.  If their first language was C++, they are going to be very nervous about casting a boolean instead of using a branch, especially if python is more of a hobby language for them than something they use in depth.

Code is for humans to read more than computers.  It's often less hassle to use a construct that works reliably across programming languages than to depend on in-depth knowledge of the specification of one language or creating a comment to that effect.  It's the same reason we use parentheses in cases where operator precedence might differ between languages.  It's less effort to read for multi-lingual programmers.

That doesn't mean we shouldn't try to write idiomatic code, just keep in mind your maintainers when either method will do.


答:
The title of your question asks "is it a good idea" but the body asks "what is the correct way to do this?" I will address the concern in the title.

At its core, a boolean is simply a single bit. However, it represents truth, not a number: while a bit may represent zero or one, it represents true and false when that bit is a boolean. What does "true" mean in the context of a number? That makes as much sense as casting the color "red" to a number.

For this reason, I argue that it is not a good idea to convert or cast a boolean to an integer or any other type. That destroys the true/false meaning of the boolean.

Java tends to be a whipping boy for implementing half-assed language decisions, but I strongly believe one thing they got right was going out of their way to treat booleans as anything but an integer. In Java, it is not possible to cast a boolean as an integer or any other type for the same reasons I already outlined.

Based on the discussion in the comments, I need to address the bigger picture of why this is the case. A cast works for an is-a relationship, and it needs to be unambiguous.

is-a: would it be possible to cast a string to a list? No, there is no is-a relationship between them. It would be possible to convert a string to a list, e.g. by expressing it as a list of characters. Casting should be used to take an object and use it as a more specific type: e.g. casting a Shape to a Square. Casting to a Color makes no sense: but retrieving the color attribute of the shape does make sense.

unambiguous: a cast needs to have no ambiguity about how to perform a conversion. Casting a string to an integer does not make sense, because additional information is needed: what radix should be used to perform the conversion? If converting a date to an integer, should the cast get the number of seconds since epoch? The hour of the day? The year? A simple cast does not and cannot have this knowledge: a conversion function is necessary.

Title: Is converting/casting a boolean to int a good idea?

Body:
Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/interpreters.

So I came across this question:

How do I convert a boolean to int in Python? Can I just do int(mybool)?

My response was to write:

```<code>1 if mybool else 0
</code>```

My reasoning was that blindly "casting" to int would rely on the internal implementation of the compiler/interpreter. And who knows, if running through a different interpreter int(mybool) might return something else. Explicitly stating the value for a "truthy" value and for a "falsey" value will always yield the expected behaviour.

This is surely something which one can consider for most languages.

Am I too picky about this? I know that I have written int(mybool) myself in the past. And that question made me think: Was that okay? Given that this is a very common case, are the compilers/interpreters smart enough to to "the right thing" for bool -> int conversions?

Now, for the special case for duck-typing languages like Python, int(mybool) might certainly be a really bad idea, but other languages are a bit clearer on their typing.


问:
Is there a good way to communicate the intent that a class only contains referentially transparent methods?
My workplace mostly uses C# for writing code. I'm trying to figure out a good way to indicate that a class with referentially transparent methods is intended to be referentially transparent (i.e., given the same set of arguments, you will always get the same return value) for future maintainers. I've considered just using static classes for classes that are intended to only contain referentially transparent methods but received pushback from my colleagues as they prefer an approach to unit testing where all classes depending on are stubbed out which they use constructor DI to accomplish. I don't see a disadvantage to not stubbing out referentially transparent functions for unit testing since they are almost always in-memory anyway but I've been unable to convince my colleagues of that.

Our class names use typical OO pattern names like DTO or Factory or Controllers and Models for namespaces. I'm not aware of any pattern names in OO that would indicate the sort of intent I am going for (i.e., to not introduce side-effecting operations or depending on things that read out of the db or filesystem).

答: I don't do much C# development but it seems to me you could define an attribute and apply it to all such classes. You could then give a thorough description of what restrictions that imposes on classes within the documentation of the attribute. That way your intent is still documented but you don't have to copy-and-paste some boilerplate about referential transparency into the documentation for all the classes.</p>


答: The best way I can imagine to do this is to use a namespace named pure or stateless or referentially-transparent (which will likely just confuse most, so stick with a simpler name than referentially transparent). With this all you need to communicate to your colleagues is "Namespace X only contains referentially transparent code" so anytime someone uses that namespace they might get the click in their head of understanding.</p>

Title: Is there a good way to communicate the intent that a class only contains referentially transparent methods?

Body:
My workplace mostly uses C# for writing code. I'm trying to figure out a good way to indicate that a class with referentially transparent methods is intended to be referentially transparent (i.e., given the same set of arguments, you will always get the same return value) for future maintainers. I've considered just using static classes for classes that are intended to only contain referentially transparent methods but received pushback from my colleagues as they prefer an approach to unit testing where all classes depending on are stubbed out which they use constructor DI to accomplish. I don't see a disadvantage to not stubbing out referentially transparent functions for unit testing since they are almost always in-memory anyway but I've been unable to convince my colleagues of that.

Our class names use typical OO pattern names like DTO or Factory or Controllers and Models for namespaces. I'm not aware of any pattern names in OO that would indicate the sort of intent I am going for (i.e., to not introduce side-effecting operations or depending on things that read out of the db or filesystem).


答:
Put a comment in the XML header of the class, to the effect of "This static class contains only referentially transparent methods, like those in the System.Math static class.  Don't put functions which cause side-effects here."

Referentially-transparent methods are the easiest of all methods to test: hand them a value, and examine the return value.  That's it.

Of course, the pushback is going to be "how do I know this 'referentially-transparent' method doesn't call other methods?"  The answer to that is that you tested those other methods, and you already know they work, right?

Further Reading

Is static universally "evil" for unit testing and if so why does resharper recommend it?


答:
Contrary to many (perhaps most) object-oriented design tutorials out there, inheritance hierarchies should not necessarily match up with a domain's real-world taxonomy.  In other words, just because all your objects are shapes in the real world doesn't necessarily mean they should all inherit from IShape in your program.  Even if they do all share an interface, just because they have similar methods doesn't mean those methods need to be part of that interface.

The trick is to look at the calling code to see what operations you really need at that point.  For example:

```<code>for shape in shapes:
  shape.doSomething()
</code>```

Are you really going to call AddValue in a loop like that?  I doubt it.  More likely, it's going to be something like Draw or GetEditControl, and AddValue will be called before it's even put into shapes, or by a dimension-aware EditControl.  In other words, IShape should only have methods that don't care about dimension, and operations that care about dimension should be handled by other interfaces.

Title: Dealing with similar objects with different method signatures

Body:
I am fairly new to OO design and have problems with the design of some software and looking for a pattern or a combination of patterns that could help me solving my problem.

I have a type that has a collection of different geometric shapes (say lines, rectangles, and cubes). I actually even have composites of these shapes.
Each shape has one or more values. A value is a coordinate (between one-dimensional for lines and three-dimensional for cubes).

All types of shapes have two methods that are essential. A method for adding values and a method for getting all values of a shape. E.g. Cube.AddValue(new Value3D{X=4,Y=7,Z=11}) or Line.AddValue(new Value1D{X=42}) respectively Cube.GetValues() would return a collection of Value3D and Line.GetValues() would return a collection of Value1D.

Since these methods have fundamentally different signatures, I can't just derive from a single interface to store all of these different objects in one collection. Splitting the collection into multiple separate collections, one for each type would be possible, but not desirable since they belong together (domain wise).

I've considered using three-dimensional values for all shapes and just ignoring Y/Z for lines/rectangles, but that isn't really nice and would actually violate the O and L in SOLID (a 4th dimension is possibly needed in the future).

Another possibility would probably be to use a generic Interface like IShape<T> where T is Value*D. This interface would look like:

```<code>public interface IShape<T> {
    public IEnumerable<T> GetValues();
    public void AddValue(T value);
}
</code>```

But this would require another, non-generic interface INonGenericShape {} because I can't use a generic interface without specifying the type. I would end up with something like this:

```<code>public class SomeShape{
    private IList<INonGenericShape> _shapes = new List<INonGenericShape>();
}
</code>```

But then I could as well use System.Object, since IShape does not provide any valuable information. So here I am, not knowing how to solve this (storing the objects in a single collection for consumers of that class). Can anyone provide some idea or insight?

Body:
Contrary to many (perhaps most) object-oriented design tutorials out there, inheritance hierarchies should not necessarily match up with a domain's real-world taxonomy.  In other words, just because all your objects are shapes in the real world doesn't necessarily mean they should all inherit from IShape in your program.  Even if they do all share an interface, just because they have similar methods doesn't mean those methods need to be part of that interface.

The trick is to look at the calling code to see what operations you really need at that point.  For example:

for shape in shapes:
  shape.doSomething()

Are you really going to call AddValue in a loop like that?  I doubt it.  More likely, it's going to be something like Draw or GetEditControl, and AddValue will be called before it's even put into shapes, or by a dimension-aware EditControl.  In other words, IShape should only have methods that don't care about dimension, and operations that care about dimension should be handled by other interfaces.


问:
Replacing string comparisons with dictionary lookups
Given 2 strings s1 and s2, if I do a simple equality check , it is considered to be O(n) when calculating algorithm efficiency. So, if I am using a brute force approach for the rotated substring question the efficiency is O(n^2) (take the 2nd substring, rotate by 1 and check. Repeat till rotations = strlen or matched)

However, a Dictionary lookup is considered O(1). If I instead used a dictionary with the sole element having a dummy value and a key = s1. Then , instead of doing a string compare I checked for the existence of s2 in the dictionary, wouldnt my complexity go down to O(n)?

Intuitively it doesnt make sense to me, so I'm guessing one of my assumptions is incorrect...

答:
A dictionary also has to do at least one comparison. If the length of the string is the variable of interest, this has to be taken into account and since the comparison is O(strlen) a lookup takes O(strlen) time too. We say hash table lookups (are expected to) take O(1) time regarding the number of entries.

Aside: A hash table with a single key would not solve the rotated substring problem. Doing this once for each rotation still takes O(strlen^2) time in total, since you do O(strlen) comparisons that take O(strlen) time each (see above). You can, however, fill one table with all of the n rotations and then takes a lookup, and under the same assumptions that imply O(1) lookup in terms of the number of keys, this takes O(strlen) time in total. However, it also takes O(strlen^2) space, which is a downside.

The reason this works for a single lookup in a single hash table of all rotations (but not for doing many lookups in single-element hash tables) is that the hashing cheaply distributes the strings in disjoint buckets, so that almost all comparisons are avoided. Strings with different hashes are culled with a hash calculation and array lookup.


问:
Controller and Model Interaction
I'm fairly new to MVC and I'm trying to get a better understanding of it. There is endless information about the theory and general responsibilities of each part of an MVC app, which I've read a good deal of, but I find myself constantly second guessing my implementation.

I currently have my application setup where my "Model" provides a number of methods that effectively do CRUD work on the application data. Methods like add_document(name, path) and update_account(id, code, name, status) At this point it works, but it feels clunky, as I effectively have to decide whether I want to write a method to update every property of a model object, or whether I want one method that can handle updating any property for a given object. These methods all interact with model objects in SQLAlchemy (A Python db toolkit and ORM). Lately I've considered the possibility of passing ORM objects back and forth between the Model and Controller. The controller would change a property, then pass the object back to the Model which would handle sessions, commits, and error conditions. While this seems so much easier than writing tons of CRUD methods, it also seems to break the division of responsibility by allowing the Controller to touch ORM objects at all...

I was hoping to get some guidance here. Are a whole ton of CRUD operations normal in MVC apps? Is it acceptable to pass ORM objects between the Model and Controller - where the Controller only ever updates properties while the model handles session and database work? I'm also open to alternative ideas about how to separate responsibilities in an elegant way.

答:
Oh-keeey.

What you are getting wrong about Model ..

You have to understand, that "Model" in MVC is not a concrete object or a class. Instead it is one of two major layer in application:

model layer contains the "business logic", it's where most of the 'interesting parts' are located

presentation layer deals with the interface through which user can interact with this "business logic"

Note: as you might already notice, it is perfectly alright to have several presentation layers in parallel. Though it's rare "in the wild".

Your presentation layer (which consists of views and controllers) interacts with model layer though services. Said services contain the interaction between domain objects and data mappers. That part goes by the name "application logic".

For example: if you had a service Library, it manipulate and the exchange between User and Book instance and pass them to different data mappers for persistence. The service doesn't really care how the isValid() method works internally for for the User instance. Neither does it cares where the user is saved, when you call mapper.store(user).

The domain objects in the model layer are the code representation of 'Domain Model' (to  learn what it is, see this book). Basically, they will contain all the business rules, conditions and ideas on which the application is based upon.

And the third major group of structures within model layer are usually data mappers. The are dealing with persistence logic goes. It's where your CRUD code actually exists. And part of persistence logic is the data integrity checks. If, when inserting new email address in the some table, you get an exception regarding UNIQUE constraint violation, data mappers is where you handle it. Whether you do it by setting an error state on the domain object which you where manipulating or you kick up/return an error code to service, it's your preference (I like the former approach).

Note: mappers can persist data in any medium that like: sql, nosql, files, remote rest api, /dev/null or crystalline fairy dust. And, if you make sure that the all have same public interface, you can use multiple data mappers on the same domain object. That would let you populate the infamous User instance from sql, cache and session. Simply by passing it to three different mappers with mapper->fetch(user) calls

So .. where are Controllers in all this

The controllers, according to MVC pattern, have a very specific responsibility: altering the state of model layer and (in rare cases) current view. That it.

Controllers do not know anything about CRUD. Controllers do not get data from model layer. Controllers do not initialize or render views. None of it.

Note: there are edge cases, where in desktop applications (or in situations when, within application's lifetime, there are multiple users interacting with it ... not applicable to web) the controller can observe model layer for changes. And, based on specific change, unlock additional functionality for same user's interaction. I have never seen it in practice.

This also means that your views must be real objects and not just dumb templates, because, since controller isn't pulling any data from model layer, views have to decide, what information they need and request it themselves.

Such fully-implemented views will usually be juggling multiple templates/layouts and presentation objects. From high orbit the will kinda resemble services, because manipulation of templates and presentation objects will vaguely resemble interaction between data mappers and domain objects.

my 2 cents

Title: Controller and Model Interaction


问:
Is often using int constants as parameters in communication between objects considered bad design?
An app I'm working on is designed with MVC. The components often interacts with each other by passing int constants, which then have to be interpreted with if statements. I'm wondering if this is considered bad OO design. (Not specifically with MVC, but in general).

For example:

When the user clicks a specific button, the controller is told by the view controller.somethingHappened(Controller.SOME_INT_VALUE);

The view uses a constant int value in the controller as a message to tell what happened. The controller then has to have a lot of if statements to interpret the message from the view. E.g.:

```<code>public void somethingHappened(int message){
    if(message == AN_INT_VALUE) doSomething();
    if(message == ANOTHER_INT_VALUE) doSomeThingElse();
    if(message == A_DIFFERENT_INT_VALUE) doAnotherThing();
}
</code>```

As a result the controller passes another int value into the model, as a message to do something. I.e. model.doSomething(Model.SOME_INT_VALUE);.

Which forces to model to also have a bunch of if statements:

```<code>public void doSomething(int message){
    if(message == AN_INT_VALUE) doSomething();
    if(message == ANOTHER_INT_VALUE) doSomeThingElse();
    if(message == A_DIFFERENT_INT_VALUE) doAnotherThing();
}
</code>```

This results in both the controller and model having a lot of ifs to interpret the messages the receive.

Is this considered ugly and/or bad design? Should I try to pass actual objects into methods, or make more specific method calls - instead of passing constants that have to be interpreted with a bunch of ifs? Or is this practice of using a lot of constants as messages considered reasonable?

If it is considered bad design, how can I avoid this?

(Please note: For the purpose of this question I'm also referring to enums).

答:
There are several choices here, in increasing order of preference (most preferable last):

Bits (flags) in an integer. Can be confusing, but allows packing a lot of them into a single int. So

DO_THIS = 1
DO_THAT = 2
DO_ANOTHER = 4
DO_ZING = 5

perform(DO_THIS | DO_THAT)

if (command && DO_THIS{ doThis(); }
...etc

Integer commands

DO_THIS = 1
DO_THAT = 2
DO_ANOTHER = 3

perform(DO_THIS, DO_THAT)

for (command in commands):
    if (command == DO_THIS) { doThis(); }

I favor strings over ints, just because they're more readable

DO_THIS = "this"
DO_THAT = "that"
...

"Typesafe" constants (in case you don't have enums around)

DO_THIS = new Object();
DO_THAT = new Object();

perform(DO_THIS, DO_THAT);

for (command in commands)
   if (command == DO_THIS) { doThis(); }

Enum is a formalization of "Typesafe constants" so use that if you have them

...

Generally, though, these schemes are useful when the calls have to be serialized & transmitted between processes. If you're just making calls from one section of code into another, you can just identify what you want done with the function names. Writing some sort of "router" function that makes a call to lower-level function replicates what the language does for you, so you might think harder about whether you need that.

...

That is, I try to keep it so that 90% of my code looks like it came straight out of "Learn Java in 30 days" (or Python, or whatever). That is, the code should just use the language in a really basic way almost all the time. There should be a pretty good reason why you can't just do it the basic way before you move to a broader generalization.


问:
Does OOP fulfill the promise of code reuse? What alternatives are there to achieve code reuse?
Perhaps the greatest promise of using object-oriented paradigm is the code reuse. Some dispute that this was achieved. Why was it (not) achieved?

Does code reuse as OOP defines it, make projects more productive?

Or more manageable? Or easier to maintain? Or with more quality?

Probably we all agree that code reuse is a good thing, but there are several ways to achieve this goal. The question is about the method of code reuse offered by OOP. Was it a good thing? Are there better methods to achieved code reuse than object orientation, sub-classing, polymorphism, etc.? What ways are better? Why?

Tell us your experience with OOP reuse or other paradigms reuse.

答: OOP gives you more ways to reuse code. That is all.

ContentLicense: CC BY-SA 2.5


答:
Model methods don't  have to be all CRUD.  What you probably need is a Service Layer.

The Service Layer provides an abstraction between your database persistence operations and your business operations.  On one side of the service layer, you have calls to CRUD methods and whatever other resources you need to fulfill service requests.  On the other side of the service layer, you have methods that execute business transactions:

```<code>public bool MoveMoney(guid SourceAccount, guidTargetAccount, SecurityToken token);
public OrderStatus PostOrder(int AccountID, int OrderID);
</code>```

Its these methods that your controller will call, not the CRUD methods.

Title: Controller and Model Interaction

Body:
I'm fairly new to MVC and I'm trying to get a better understanding of it. There is endless information about the theory and general responsibilities of each part of an MVC app, which I've read a good deal of, but I find myself constantly second guessing my implementation.

I currently have my application setup where my "Model" provides a number of methods that effectively do CRUD work on the application data. Methods like add_document(name, path) and update_account(id, code, name, status) At this point it works, but it feels clunky, as I effectively have to decide whether I want to write a method to update every property of a model object, or whether I want one method that can handle updating any property for a given object. These methods all interact with model objects in SQLAlchemy (A Python db toolkit and ORM). Lately I've considered the possibility of passing ORM objects back and forth between the Model and Controller. The controller would change a property, then pass the object back to the Model which would handle sessions, commits, and error conditions. While this seems so much easier than writing tons of CRUD methods, it also seems to break the division of responsibility by allowing the Controller to touch ORM objects at all...

I was hoping to get some guidance here. Are a whole ton of CRUD operations normal in MVC apps? Is it acceptable to pass ORM objects between the Model and Controller - where the Controller only ever updates properties while the model handles session and database work? I'm also open to alternative ideas about how to separate responsibilities in an elegant way.

Body:
Model methods don't  have to be all CRUD.  What you probably need is a Service Layer.

The Service Layer provides an abstraction between your database persistence operations and your business operations.  On one side of the service layer, you have calls to CRUD methods and whatever other resources you need to fulfill service requests.  On the other side of the service layer, you have methods that execute business transactions:

public bool MoveMoney(guid SourceAccount, guidTargetAccount, SecurityToken token);
public OrderStatus PostOrder(int AccountID, int OrderID);

Its these methods that your controller will call, not the CRUD methods.