答: Once we've asserted that both arrays have the same length, we can duplicate one array, and the problem is reduced to the substring search problem "ABCD" in "DABCDABC". There are a variety of algorithms available for that. Note that unless the data can be mapped to simple strings, manually implementing the chosen algorithm would be better. In this case, you would not physically duplicate the array but rather use index mod length for accessing items.

Title: Best algorithm to determine whether two arrays can be the same in a circular queue

Body:
I'm trying to figure out an efficient way to determine whether two distinct arrays of the same size can be shifted to form the same circular queue. For example:

```<code>Array1 = ['A','B','C','D']
Array2 = ['D','A','B','C']
</code>```

Can form the same circle if both ends are joined together:

I thought that one way would be to loop through one of the arrays while one remains constant, for example:

```<code>while Array1 is not = Array2 and iterations < Length of Array1
      temporary = Array1[last]
      for index is 0, add 1, before index = last
           temporary[index] becomes temporary[index+1]
      Array1[0] = temporary
      if Array1 == Array2 return TRUE
return FALSE
</code>```

Is there a more efficient way? I would need to do this check for several arrays among each other and remove duplicates. Plain speech, pseudocode or Python/C# data structures/code would be appreciated.


问:
Hardcoding strings that will never change
So, in my efforts to write a program to conjugate verbs (algorithmically, not through a dataset) for French, I've come across a slight problem.

The algorithm to conjugate the verbs is actually fairly simple for the 17-or-so cases of verbs, and runs on a particular pattern for each case; thus, the conjugation suffixes for these 17 classes are static and will (very likely) not change any time soon. For example:

```<code>// Verbs #1 : (model: "chanter")
    terminations = {
        ind_imp: ["ais", "ais", "ait", "ions", "iez", "aient"],
        ind_pre: ["e", "es", "e", "ons", "ez", "ent"],
        ind_fut: ["erai", "eras", "era", "erons", "erez", "eront"],
        participle: ["é", "ant"]
    };
</code>```

These are inflectional suffixes for the most common class of verb in French.

There are other classes of verbs (irregulars), whose conjugations will also very likely remain static for the next century or two. Since they're irregular, their complete conjugations must be statically included, because they can't reliably be conjugated from a pattern (there are also only [by my count] 32 irregulars). For example:

```<code>// "être":
    forms = {
        ind_imp: ["étais", "étais", "était", "étions", "étiez", "étaient"],
        ind_pre: ["suis", "es", "est", "sommes", "êtes", "sont"],
        ind_fut: ["serai", "seras", "sera", "serons", "serez", "seront"],
        participle: ["été", "étant"]
    };
</code>```

I could put all this into XML or even JSON and deserialize it when it needs to be used, but is there a point? These strings are part of natural language, which does change, but at a slow rate.

My concern is that by doing things the "right" way and deserializing some data source, I've not only complicated the problem which doesn't need to be complicated, but I've also completely back-tracked on the whole goal of the algorithmic approach: to not use a data source! In C#, I could just create a class under namespace Verb.Conjugation (e.g. class Irregular) to house these strings in an enumerated type or something, instead of stuffing them into XML and creating a class IrregularVerbDeserializer.

So the question: is it appropriate to hard-code strings that are very unlikely to change during the lifetime of an application? Of course I can't guarantee 100% that they won't change, but the risk vs cost is almost trivial to weigh in my eyes - hardcoding is the better idea here.

Edit: The proposed duplicate asks how to store a large number of static strings, while my question is when should I hard-code these static strings.

答:
Strings should be extracted to a configuration file or database when the values could change independently from the program logic.

For example:

Extracting UI texts to resource files. This allows a non-programmer to edit and proof-read the texts, and it allows adding new languages by adding new localized resource files.

Extracting connection strings, urls to external services etc. to configuration files. This allows you to use different configurations in different environments, and to change the configurations on the fly because they may need to change for reasons external to your application.

A spell checker which has dictionary of words to check against. You can add new words and languages without modifying the program logic.

But there is also a complexity overhead with extracting to configuration, and it doesn't always make sense.

Strings may be hardcoded when the actual string cannot change without changing the program logic.

Examples:

A compiler for a programming language. The keywords are not extracted to a configuration, since each keyword have specific semantics which has to be supported by code in the compiler. Adding a new keyword will always require code changes, so no value in extracting the strings to a configuration file.

Implementing a protocol: Eg. a HTTP client will have hardcoded strings like "GET", "content-type" etc. Here the strings are part of the specification of the protocol, so they are the parts of the code least likely to change.

In your case I think it is clear that the words are an integrated part of the program logic (since you are building a conjugator with specific rules for specific words), and extracting these words to an external file has no value.

If you add a new language you will need to add new code anyway, since each language have specific conjugation logic.

Some have suggested that you could add some kind of rule engine which allows you to specify conjugation rules for arbitrary languages, so new languages could be added purely by configuration. Think very carefully before you go down that road, because human languages are wonderfully weird so you need very expressive rule engine. You would basically be inventing a new programming language (a conjugation DSL) for dubious benefit. But you already have a programming language at your disposal which can do anything you need. In any case, YAGNI.

ContentLicense: CC BY-SA 3.0


问:
Difference between PyPy and JVM
From my understanding the default Python interpreter(CPython) compiles source code into bytecode and then interprets the bytecode into machine code. PyPy on the other hand makes use of JIT to optimize often interpreted bytecode into compiled machine code. How is this different then the JVM? The JVM is an interpreter + compiler. It compiles source code to bytecode and then optimizes the often interpreted bytecode into compiled machine code. Is there any other difference?</p>

答:
The concept is only similar in the broadest strokes. Yes, both interprets a simplified program representation called bytecode and compile parts of that to optimized machine code, but that's there is stops. For starters, "JVM" is a catch-all term for all implementations of a standard. There is only one PyPy. There is no one JVM.

In addition, the compilation is done rather differently. Most JVMs are so-called method JIT compilers, that is they compile and optimize individual methods (modulo inlining). PyPy is a so-called tracing JIT, it compiles a part of the dynamic execution of the program, i.e., it follows the control flow wherever it takes us, be it through fifty different methods or covering only one small part of a larger method.

Title: Difference between PyPy and JVM


问:
Unit of Design Versus Unit of Re-use. What is the difference?

Contemporary object-oriented programming languages employ the class as  the unit of reuse.  At the same time, the class is also the unit of  design.  This implies that to reuse a class, the design of the class must  fit the design in which it will be reused.  While this serves  planned reuse, it hampers unplanned reuse.  Obviously,  unplanned reuse is much more important if widespread reuse is  desired.

  (From:http://gerbil.org/tom)

What is the difference between both of them?

答:
If the class is the unit of design, it mes that you design your code one class at a time. You should be able to old pretty much the entire purpose and implementation of the class in hour head at one time, you would commit its code to the project all at once, or within a short time, etc.

If a class is the unit of reuse, it just means that when someone wants to reuse your code, he's supposed to take the entire class and do something with it, e.g. call its methods or maybe inherit from it - not to copy one of its method and make modifications. "Class as the unit of reuse" is a popular notion because it means you could distribute your class in a compiled form and have it reused without exposing the source code (this is less convincing now than it used to be, because so many practitioners have embraced the idea of open-source software, but you'd be surprised how many decision-makers are ridiculously behind the times).

Obviously, these two ideas don't have to be true at the same time. You could design an entire module at a time and still want to reuse only a little code snippet from one corner. Therefore it's a good idea to have a clear conception of what a class is and how it should be used by authors, co-developers and application programmers.


问:
Business concept design vs logical database design
Good day. I need help for a specific case. A little background: We have an existing app, it is like a PDF viewer, and you can draw freehand, highlight, add highlight with notes, add action items, etc.

In this discussion, I'll discuss the two database tables 1) ACTION_ITEM table containing the list of action items of a document, and 2) HIGHLIGHT table containing the highlight and the notes.

The difference between a highlight note and an action item is that in action item, you can assign it to a person, specify a due date, and mark it as completed.

Currently we added an enhancement, for the end user to convert a highlight note to an action item. So we added a checkbox "[ ] Action Item". When you convert to an action item, the UX of it will still look the same: it visually still looks like a note, it is still associated with a highlight, and it still located on a page, except that it has the "Action Item" checked. (Our "usual" action item, is not associated to a page).

The programmers (including me) already coded the enhancement (this is in multiple platforms), in such a way we knew best: We added the needed new columns to HIGHLIGHT table: due date, assigned person, status and an action item indicator.

Now here's the tricky part, there's an ongoing design discussion to change the physical design to transfer the highlight note marked as an action item to ACTION_ITEM table. This means, copying all the columns needed in the HIGHLIGHT table like highlight rectangle, note location, page number, document id, etc and copying it to ACTION_ITEM table.

This only applies to highlight notes marked as an action item. If the highlight note is not marked as an action item, then we still need to store it in HIGHLIGHT table. Currently, marking a note as an action item, we just change a column, in the new design, we have to transfer the entire record to another table.

Not only that the physical design will change, but all logic related to its storage and retrieval (which is a lot).

The reason is, the Systems Analyst said that instead of programming for convenience, we need to align the physical design to the business concept. In this case, an Action Item is a different business concept so it needs to be in the ACTION_ITEM table.

My question is, is Systems Analyst correct? Do we merge a physically different entities in the same table, just because it's the same business concept? Seems illogical to me as a programmer. It's not merely for convenience, it's for efficiency.

答:
I think the SA is right. (in that you should have actions in the actions table) But for more concrete reasons than just 'align with business definitions'

1: By adding the exta cols to highlight you have broken the normalisation of that table.

2: you presumably do stuff with actions, now you have to check two places to get them all. breaking the single source of truth principle.

Obviously the same reasons would apply to 'copying the highlight fields to action' so your SA is just as wrong if there are suggesting that

Instead I would have added an association between actions and highlights.

ie.

```<code>ACTION_ITEM
  Id
  FieldsForAction

HIGHLIGHT
  Id
  FieldsForHighlight

HighlightsWithActions
  HighlightId
  ActionItemId
</code>```

so when you tick the highlight to make it an action, you populate a new ActionItem and add a row to HighlightsWithActions specifinging the selected highlight and the Id of the new ActionItem you created.

You can add unique indexes to limit the relationship to a 1-0/1 or 1-many or many-many as required

In the long run this will make the programming easier as the business will ask for new stuff like 'make all the actions flash red on tuesdays' etc

Body:
I think the SA is right. (in that you should have actions in the actions table) But for more concrete reasons than just 'align with business definitions'

1: By adding the exta cols to highlight you have broken the normalisation of that table.

2: you presumably do stuff with actions, now you have to check two places to get them all. breaking the single source of truth principle.

Obviously the same reasons would apply to 'copying the highlight fields to action' so your SA is just as wrong if there are suggesting that

Instead I would have added an association between actions and highlights.

ie.

ACTION_ITEM
  Id
  FieldsForAction

HIGHLIGHT
  Id
  FieldsForHighlight

HighlightsWithActions
  HighlightId
  ActionItemId

so when you tick the highlight to make it an action, you populate a new ActionItem and add a row to HighlightsWithActions specifinging the selected highlight and the Id of the new ActionItem you created.

You can add unique indexes to limit the relationship to a 1-0/1 or 1-many or many-many as required

In the long run this will make the programming easier as the business will ask for new stuff like 'make all the actions flash red on tuesdays' etc


答:
Despite the fact the original cite is ~15 years old, I doubt classes have ever been "the primary units of reuse" outside of some academic books and schools. The object-oriented black-box unit of reuse of today is typically a  component - which means a self-contained library with a contract, an interface with a clear syntactical and semantical description, and machine readable meta information which allows some kind of introspection. Some of the available component technologies of today allow programming language independendent reuse.

A typical component consists of one or more classes (and can at least theoretically be implemented without any classes at all), but "the class" is typically just a "unit of design" (a tool to give your code more structure), not a "unit of reuse". For some components, one class may be enough, but that is more an exception than the regular case.

Furthermore, other, older forms of creating reusable units like building libraries or modules are still popular, but those do not even need the notion of object-orientation or classes. When you look today at the big collections of reusable software available at the web, the "reusable units" which are single classes are only a small percentage, compared to the total number of reusable components, libraries or modules. That should make the difference very clear.

Title: Unit of Design Versus Unit of Re-use. What is the difference?

Body:
Contemporary object-oriented programming languages employ the class as  the unit of reuse.  At the same time, the class is also the unit of  design.  This implies that to reuse a class, the design of the class must  fit the design in which it will be reused.  While this serves  planned reuse, it hampers unplanned reuse.  Obviously,  unplanned reuse is much more important if widespread reuse is  desired.

  (From:http://gerbil.org/tom)

What is the difference between both of them?


问:
Why doesn't Haskell have a 'format' function for string interpolation?
I'm trying to use Shake and I stumbled upon the following problem: there's no easy and convenient way to interpolate a string. I know about Text.Printf — it's not what I'm looking for. The interpolation syntax I'm talking about is like this:

(Make)

```<code>HEADERS_DIR := /some/path/to/dir

CFLAGS := "-g -I$(HEADERS_DIR) -O2"
</code>```

(Python)

```<code>headers_dir = "/some/path/to/dir"

cflags = "-g -I{headers_dir} -O2".format(**locals())
</code>```

And now compare this to possible Haskell's solution. Firstly:

```<code>$ cabal install interpolatedstring-perl6
$ ghci -XExtendedDefaultRules -XQuasiQuotes
</code>```

And then:

```<code>> import Text.InterpolatedString.Perl6 (qq)
> let headers_dir = "/path/to/some/dir"
> [qq| -g -I$headers_dir -O2 |] :: String
</code>```

While I think Make goes maybe a step too far in its eagerness to interpolate even when not asked, I wonder why Haskell doesn't have a format function like Python does. It could parse the supplied string and pull the value with same name as referenced in pattern:

```<code>let headers_dir = "/path/to/some/dir"
format "-g -I$headers_dir -O2"
</code>```

Is there a specific reason why it's not implemented, or everyone is just happy with Text.Printf's verbosity and/or lengthy setup of interpolation libraries?

Update: A lot of people misinterpret the question as asking about general string formatting, with possibility of precision specification in case of integers, etc. The examples provided demonstrate one specific case of interpolation, which is just "substitute the result of show a at the place of name". It does allow for simpler syntax, and it does not use a variadic function per se.

答:
In Python: the language actually specifies that variables can be referenced by name at runtime. In Haskell: names for everything except top level bindings tend to get erased during compile time and replaced with numeric references.

In your example: headers_dir = "/path/to/some/dir" becomes something a bit more like 0x09039dc0 = "/path/to/some/dir" by the time the code is actually run. This means that any reference to headers_dir has to get replaced by the numeric reference at compile time, which is what the quasiquoter was for.

Without using quasiquoters or other parts of Template Haskell; you'd have to do something to manually preserve the variable names, such as putting the values in a map.


问:
Provide part of context to class using interface
Currently I have class Context which I inject in some places in my code, like:

```<code>protected override object GenerateSomething (object input, Context ctx)
</code>```

Depending on Context, Generate method gives different results.

But, would it be better to create interface IGeneratorContext like this:

```<code>public interface IGeneratorContext
{
    ISomething1 GetX ();
    ISomething2 GetY ();
}
</code>```

And change method signature to this:

```<code>protected override object GenerateSomething (object input, IGeneratorContext ctx)
</code>```

And I will still pass Context object to this method. Ofcourse I wil add interface IGeneratorContext to Context class. So now I will pass same object, but as interface with less methods exposed.

Is it a good idea?

答:
Yes, it would be a better option to use an interface.

As you have already pointed out yourself, by using an interface you have better control over which methods are exposed. But another important aspect of using an interface is loose coupling.

This is because the injected class no longer has to be a child of a perticular class. This means that the injected class can inherit another class, and it means your code will be easier to extend in the future.


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答:
this is coming with the experience. when you're a newbie, or you jump into other programming language is a little bit difficult.
when you have several years working with a language, then is easier to understand. </p>

<p>but, as a general rule, I'm firing up the debugger, and start to understand what's happening in it. also it is VERY IMPORTANT to comment your code, and to work on documented code. </p>

ContentLicense: CC BY-SA 2.5

Body:
this is coming with the experience. when you're a newbie, or you jump into other programming language is a little bit difficult.
when you have several years working with a language, then is easier to understand.

but, as a general rule, I'm firing up the debugger, and start to understand what's happening in it. also it is VERY IMPORTANT to comment your code, and to work on documented code.


问:
YAML: translating free-flowing text from XML
I'm studying YAML as a replacement for XML, but I'm experiencing difficulties when dealing with elements containing free-flowing text with embedded elements.  For instance, the following XML document:

```<code>    <text>
    This is an example text, spanning multiple lines, and it has embedded elements
    like this and <b>this</b>.  There is also a list:
         <quote>
            <text>The text of the quote, spanning multiple lines, and it has
            embedded elements like <c p="value">this</c> and <b>this</b></text>
            <author>The Author of this quote</author>
        </quote>
    Text continues here.
    </text>
</code>```

I don't know how to convert the embedded elements in YAML.  My understanding is that the above XML document segment translates to something like this (except for the embedded elements):

```<code>    text: >
            This is an example text, spanning multiple lines, and it has embedded
            elements like this and <b>this</b>.  There is also a
            list:
                 quote:
                    text: >
                            The text of the quote, spanning multiple lines,
                            and it has embedded elements like <c p="value">this</c>
                            and <b>this</b>
                    author: The Author of this quote
            Text continues here.
</code>```

Also, is indentation not needed in some places?

答:
If an XML/HTML/SGML parser, for some programming language X, generically parses your kind of input (instead of generating abstracted objects), you normally have the tags translated to the mapping construct for X, with the children tags and string elements as a sequence construct for X (as these need ordering), with the attributes of the tag some special first element of that sequence (if attributes are available).

Such a hierarchy is a perfect match for YAML¹:

```<code>text:
- |-
  This is an example text, spanning multiple lines, and it has embedded elements
  like
- a:
  - .attribute:
      p: value
  - this
- and
- b: this
- '.  There is also a list:'
- quote:
  - text:
    - |-
      The text of the quote, spanning multiple lines, and it has
              embedded elements like
    - c:
      - .attribute:
          p: value
      - this
    - and
    - b: this
  - author: The Author of this quote
- Text continues here.
</code>```

The literal block has been used here to preserve newlines in the original data, but folded could be used as well.

This YAML can be used to regenerate the orginal XML/HTML/SGML structure except for some stripped and collapsed white-space information, which normally do not affect e.g. rendering of HTML. The above YAML is not the representation of XML/HTML/SGML in YAML, just one of the possible ways of doing that.

As for your second question:

is indentation not needed in some places?

As you can see from the output, indentation is not always needed, the sequence elements under the key text: are not indented. But if you outdent, then you always end a collection (sequence/mapping).

¹ This is the output of yaml from-html --no-body input.xml with input.xml containing your XML document. yaml is a command that is part of my python package ruamel.yaml

Body:
I'm studying YAML as a replacement for XML, but I'm experiencing difficulties when dealing with elements containing free-flowing text with embedded elements.  For instance, the following XML document:

```<code>    <text>
    This is an example text, spanning multiple lines, and it has embedded elements
    like <a p="value">this</a> and <b>this</b>.  There is also a list:
         <quote>
            <text>The text of the quote, spanning multiple lines, and it has
            embedded elements like <c p="value">this</c> and <b>this</b></text>
            <author>The Author of this quote</author>
        </quote>
    Text continues here.
    </text>
</code>```

I don't know how to convert the embedded elements in YAML.  My understanding is that the above XML document segment translates to something like this (except for the embedded elements):

```<code>    text: >
            This is an example text, spanning multiple lines, and it has embedded
            elements like <a p="value">this</a> and <b>this</b>.  There is also a
            list:
                 quote:
                    text: >
                            The text of the quote, spanning multiple lines,
                            and it has embedded elements like <c p="value">this</c>
                            and <b>this</b>
                    author: The Author of this quote
            Text continues here.
</code>```

Also, is indentation not needed in some places?

Body:
If an XML/HTML/SGML parser, for some programming language X, generically parses your kind of input (instead of generating abstracted objects), you normally have the tags translated to the mapping construct for X, with the children tags and string elements as a sequence construct for X (as these need ordering), with the attributes of the tag some special first element of that sequence (if attributes are available).

Such a hierarchy is a perfect match for YAML¹:

text:
- |-
  This is an example text, spanning multiple lines, and it has embedded elements
  like
- a:
  - .attribute:
      p: value
  - this
- and
- b: this
- '.  There is also a list:'
- quote:
  - text:
    - |-
      The text of the quote, spanning multiple lines, and it has
              embedded elements like
    - c:
      - .attribute:
          p: value
      - this
    - and
    - b: this
  - author: The Author of this quote
- Text continues here.

The literal block has been used here to preserve newlines in the original data, but folded could be used as well.

This YAML can be used to regenerate the orginal XML/HTML/SGML structure except for some stripped and collapsed white-space information, which normally do not affect e.g. rendering of HTML. The above YAML is not the representation of XML/HTML/SGML in YAML, just one of the possible ways of doing that.

As for your second question:

is indentation not needed in some places?

As you can see from the output, indentation is not always needed, the sequence elements under the key text: are not indented. But if you outdent, then you always end a collection (sequence/mapping).

¹ This is the output of yaml from-html --no-body input.xml with input.xml containing your XML document. yaml is a command that is part of my python package ruamel.yaml


问:
If possible, would it be a bad practice to use Nullable for non value types?

After writing this question I found out that Nullable<T> has a type constraint of struct on T so you cannot actually use Nullable for
  reference types. However, some good answers interpreted the questions
  as 'if you could' or 'if you would write your own Nullable or
  NonNullable type'. This interpretation has lead to some nice answers
  so I've decided to not close or delete the question.

I know the nullable construct in C# was introduced to support null for value types. However, the language does not seem to have a problem with using nullable on other types. I wonder if this is a bad practice. I've come up with some arguments for both sides, but I can't decide.

Pros

Foo? x  makes it exceptionally clear that a variable can be null.

Cons

If Foo is not a value type we create a struct with a reference type which is a bad practice.

Why wrap a variable that can already be null with more boilerplate code. Comments or naming can already indicate that the value can be null.

Not marking the object as nullable does not guarantee that it will not be null. So inconsistent use will lead to confusion.

Performance overhead? (Extremely neligible in most cases).

It makes the code slightly harder to read

With nullable

```<code>Foo? x;

// <snip>

x = null;

// <snip>

if(x.HasValue) { x.Value.Bar(); }
</code>```

Without

```<code>Foo x; // Might be null

// <snip>

x = null;

// snip>

if(x != null) { x.Bar(); }
</code>```

答:
This is not a question of good or bad pratices.

Nullable (the type that is behind the type?notation) does not allow reference types:

public struct Nullable where T : struct

It's really that easy. Only value types can be nullable using the Nullable<T> type.


问:
distinguish requests from the same vehicle
I am implementing an small app to track buses based on Crowdsorcing. The riders send data long, lat, mac, route to the server as JSON string.

In my database I have table bus to insert the transmitted data. One record in the bus table represents one bus vehicle. Therefore, one rider should  update the record of the bus vehicle in the case of many riders are sitting in the same bus and their devices transmit data to the server from the same bus.

To reach that I have tried to filter the requests from the same bus with the aid of the haversine formula but it is overkill for short distance. Is there another way to reach that without taking into consideration the distance between the sender of the requests?

答:
As I understand the problem you want to associate the position/time data from the device with a bus.

presumably you have the timetable information server side, so you know how many buses there are and roughly what times they are at the various stops.

you have multiple position/time/device messages with a degree of error in the position/time measurement which may come from:

A: 2 devices in a single bus - appears that there are 2 buses at the same location

B: 2 buses at the same location, 1 device per bus - appears that there is 1 bus

You can only resolve these scenarios with additional data. ie. if you have two devices which approach and then separate, you can infer that there are two buses. If the two devices closely match position (i would just use euclidean maths) over a period of time consistent with a bus timetable you can infer that they are on the same bus.

Due to the large errors in gps location, in cities particularly, the chances are you are going to get a lot of inconsistent data. If you try and display this in real time the visualization will flicker as you reinterpret the data over time.

You can get around this by trusting the timetables more than the data. I would try and detect events from the aggregate data

Bus stopped between stops for more than x amount of time

Bus in slow traffic. significantly lagging time table

unless this type of thing occurs just show the bus position based on the timetable


答:
Nullable<T> has a constraint which won't let you use it with classes, but only structs.

If T wasn't constrained, using Nullable<T> for classes would be a mistake anyway. Your intent is to simplify your code, but you're actually making it harder.

In C#, classes are always nullable. By telling that the nullable entity is nullable, you're not really making your code more explicit for the maintainers, since the purpose of such construct is all but clear. It's like if I were documenting that a method which accepts int as a parameter should take a value between int.MinValue and int.MaxValue. Does it make the code clearer? Not really, because it is just redundant with the language rules.

Usually, what C# developers look for is the opposite thing: how to specify that something cannot be null while being a class. For example, how do you tell that public Product CreateProduct(string name, Price price) can't have a null name, nor a null price and cannot return a null?

Code contracts is one way to go, but are obviously limited to pre-conditions, post-conditions and invariants. If you need to globally specify that Price can never ever be a null because it doesn't make sense in a context of your business logic, then you might end up moving Price from a class to a struct.

Title: If possible, would it be a bad practice to use Nullable for non value types?

Body:
After writing this question I found out that Nullable<T> has a type constraint of struct on T so you cannot actually use Nullable for
  reference types. However, some good answers interpreted the questions
  as 'if you could' or 'if you would write your own Nullable or
  NonNullable type'. This interpretation has lead to some nice answers
  so I've decided to not close or delete the question.

I know the nullable construct in C# was introduced to support null for value types. However, the language does not seem to have a problem with using nullable on other types. I wonder if this is a bad practice. I've come up with some arguments for both sides, but I can't decide.

Pros

Foo? x  makes it exceptionally clear that a variable can be null.

Cons

If Foo is not a value type we create a struct with a reference type which is a bad practice.

Why wrap a variable that can already be null with more boilerplate code. Comments or naming can already indicate that the value can be null.

Not marking the object as nullable does not guarantee that it will not be null. So inconsistent use will lead to confusion.

Performance overhead? (Extremely neligible in most cases).

It makes the code slightly harder to read

With nullable

```<code>Foo? x;

// <snip>

x = null;

// <snip>

if(x.HasValue) { x.Value.Bar(); }
</code>```

Without

```<code>Foo x; // Might be null

// <snip>

x = null;

// snip>

if(x != null) { x.Bar(); }
</code>```


答:
As others have said, this isn't possible, but there are a couple of easy constructs you can create yourself that achieve similar aims.

Maybe<T>

```<code>public struct Maybe<T> where T : class
{
   public bool HasValue { get; private set; }

   private readonly T _value;
   public T Value
   {
       get
       {
           if(!HasValue){throw new InvalidOperationException();}
           return _value;
       }
   }

   public Maybe(T value) : this()
   {
       if(value==null) { throw new ArgumentNullException("value"); }
       HasValue = true;
       _value = value;
   }
}
</code>```

(This could also be implemented other ways, such as an IEnumerable<T> with the constraint that it has exactly 0 or 1 items)

NotNull<T>

```<code>public class NotNull<T> where T : class
{
    public readonly T Value;

    public NotNull(T value)
    {
        if(item == null){ throw new ArgumentNullException("value"); }
        Value = value;
    }
}
</code>```

Maybe<T> essentially just reimplements Nullable<T> for reference types. It has similar advantages and disadvantages to the ones described in your post. It's probably only valuable if you have a convention throughout your project to use it for any value where null is a valid value.

NotNull<T> is likely to be more directly what you want, as MainMa stated. By passing around values wrapped in this type you can remove the need to check whether a value is null in a guard clause. However, there's no way to completely prevent a NotNull<T> from itself being null. You can't make it a struct because of the requirement of a default constructor, which would leave Value null.

(EDIT: As others have pointed out, in C# 6 you will be able to have a parameterless constructor for a struct, but it will not be used when initializing arrays or getting the result of default(T), so you still can't really rely on the guarantee that Value won't be null)

So while both of these potentially add some value in signalling whether null should be considered valid or not, they're both limited in that they require constant adherence to a convention, in addition to the boilerplate and readability issues. Whether the trade-off is worth it would be a matter of judgement, but remember that code contracts or other static analysis tools also exist as a possible alternative way of addressing this issue.

Body:
As others have said, this isn't possible, but there are a couple of easy constructs you can create yourself that achieve similar aims.

Maybe<T>

public struct Maybe<T> where T : class
{
   public bool HasValue { get; private set; }

   private readonly T _value;
   public T Value
   {
       get
       {
           if(!HasValue){throw new InvalidOperationException();}
           return _value;
       }
   }

   public Maybe(T value) : this()
   {
       if(value==null) { throw new ArgumentNullException("value"); }
       HasValue = true;
       _value = value;
   }
}

(This could also be implemented other ways, such as an IEnumerable<T> with the constraint that it has exactly 0 or 1 items)

NotNull<T>

public class NotNull<T> where T : class
{
    public readonly T Value;

    public NotNull(T value)
    {
        if(item == null){ throw new ArgumentNullException("value"); }
        Value = value;
    }
}

Maybe<T> essentially just reimplements Nullable<T> for reference types. It has similar advantages and disadvantages to the ones described in your post. It's probably only valuable if you have a convention throughout your project to use it for any value where null is a valid value.

NotNull<T> is likely to be more directly what you want, as MainMa stated. By passing around values wrapped in this type you can remove the need to check whether a value is null in a guard clause. However, there's no way to completely prevent a NotNull<T> from itself being null. You can't make it a struct because of the requirement of a default constructor, which would leave Value null.

(EDIT: As others have pointed out, in C# 6 you will be able to have a parameterless constructor for a struct, but it will not be used when initializing arrays or getting the result of default(T), so you still can't really rely on the guarantee that Value won't be null)

So while both of these potentially add some value in signalling whether null should be considered valid or not, they're both limited in that they require constant adherence to a convention, in addition to the boilerplate and readability issues. Whether the trade-off is worth it would be a matter of judgement, but remember that code contracts or other static analysis tools also exist as a possible alternative way of addressing this issue.


答:
Asking the author

Going with the debugger through in different scenarios

Saving discoveries in written form

Learning by trying to add/change something and seeing where it leads

Doing some pair programming with an experienced colleague or the author

Title: How do you go about understanding others' code?

Body:
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?


问:
Time estimating of a complex bug investigation (not a straight-forward one)
(It is not a duplicate: Bug investigation is much more non-deterministic than a defined development task where things to be done are specified. Investigation is about narrowing a huge search space, which is different from building software. We cannot compare Memory Corruption bugs, C/C++ Undefined Behaviors, and Multi-Thread data races to scope-limited development tasks).

It's not the first time that my superiors are asking for an estimation when dealing about bug investigation. Just like it was a delimited development task.

I tend to prefer a scale of complexity. Something like: Easy, Not That Easy, Hazy, Difficult, and Really Difficult. And giving a time estimate only for easy investigations.

For simple investigations, I do agree that it is feasible. But I have no success in explaining them that a complex investigation is a cycling process:

Reason about the facts, the code, the trouble

Make hypothesis

Find ways to measure the hypothesis by facts (traces, logs, debug...)

If facts are clear and hypothesis is false, restart at 1.

It's a rather scientific/rationalist process indeed.

What other arguments could I tell, so as to explain the uncertainty in the very process of bug investigation?

答:
Time estimation for completion of tasks in software development is a dark art indeed. I think your arguments are good, but you forgot one critical one:

However much time you think it's going to take, multiply that by two.

I've found this to work quite well. Things will always take longer than you think it will, especially in software development.


答:
This isn't practically useful to you, but I wouldn't sink to the level of explaining to non-technical coworkers why certain technical tasks are harder than others. The point of hiring specialists for programming tasks who are better at technical things and worse at business or management things than their employers is that thy are better at them. To a large part, understanding why a defect arises equates to being able to fix it, and to a lesser degree to being able to avoid similar errors in the future.

Shortly and brutally, if your superiors could understand why some debugging tasks are so hard, they would be able to perform those tasks themselves - which they aren't, since they hired you. It's hard for anyone to accept that there are distinctions that they cannot appreciate, so there is little point explaining to a manager that you are having difficulties that you can't explain to him. The best thing you can do is to rise to his level of the view and tell him, "Look, I know this sounds lame, but I cannot tell you very well how long this will take no matter what the incentive". Once you've said this in the cases where it's true, and they have seen that it is actually true (because your effort did vary unpredictably), maybe they'll begin to believe you when you say that you dobn't know something. But I wouldn't hold my breath. Saying "I don't know" to something in a competetive environment is very hard to do, and many professionals avoid doing it at all costs; and so they tend to believe that it isn't true when someone else is saying it either. Strange, but (in my previous experience) all too true.

Title: Time estimating of a complex bug investigation (not a straight-forward one)

Body:
(It is not a duplicate: Bug investigation is much more non-deterministic than a defined development task where things to be done are specified. Investigation is about narrowing a huge search space, which is different from building software. We cannot compare Memory Corruption bugs, C/C++ Undefined Behaviors, and Multi-Thread data races to scope-limited development tasks).

It's not the first time that my superiors are asking for an estimation when dealing about bug investigation. Just like it was a delimited development task.

I tend to prefer a scale of complexity. Something like: Easy, Not That Easy, Hazy, Difficult, and Really Difficult. And giving a time estimate only for easy investigations.

For simple investigations, I do agree that it is feasible. But I have no success in explaining them that a complex investigation is a cycling process:

Reason about the facts, the code, the trouble

Make hypothesis

Find ways to measure the hypothesis by facts (traces, logs, debug...)

If facts are clear and hypothesis is false, restart at 1.

It's a rather scientific/rationalist process indeed.

What other arguments could I tell, so as to explain the uncertainty in the very process of bug investigation?


答:
The unit of design means when you sit down to design a new program, you are basically deciding on a set of classes you will include.

The unit of reuse means if you want to reuse functionality someone else has written, the smallest unit you can pull into your new program without making a new copy of the code is an entire class.  As Doc Brown pointed out, often because of coupling that unit is even larger.  You can't reuse just one method, or just the data structure without any methods, as is common in functional and procedural paradigms.

Most OO programmers don't realize how big of a problem this actually causes for reuse.  Generally, classes must be carefully designed with reusability in mind, and mainly only library designers go to the trouble.

The smaller the unit of reuse, the smaller the probability that the unit is specific to a single application.  That's why the most successful reused code uses very small, widely-accepted, general-purpose interfaces.  For example, a simple compare interface on a type allows that type to be reused in a wide range of existing code, from sorting algorithms to data structures like binary search trees.  Note, however, that the reused code must have been initially designed in order to take advantage of that interface.


答:
Combine two approaches: the "fixed time estimate" and the "I don't know" approach without literally saying I don't know. Let's face it, if you knew exactly what is causing the bug you wouldn't have written it that way in the first place (yes, I know we don't always fix our own code, but isn't cleaning up someone else's mess even worse?).

Get into the habit of responding to bug time quote requests with, "I'll take a look at it and let you know how long it will take by ." People want to know that you care enough by demonstrating you're taking steps to solving the problem and that you're prioritizing their task appropriately. Making promises (and they are promises in their mind) you can't keep is going to decrease their level of trust in you.

Don't forget to reorganize your other commitments. In simple terms, I can't fix your new found bug and deliver a new feature at the same time. Which one do you want me to do first? Hopefully, they'll get the bug out of the way, but you never know.

They don't want a technical explanation. When a non-technical users asks, "Why is this going to take so long?" they don't necessarily want a technical answer and they really don't want details. By taking time to investigate the error and then giving a time estimate afterwards, you can also summarize the solution. There may be multiple areas of the app that need to be altered (The technical debt has now come due.), patching other technology, etc.


答:
Looking for a solution to a problem can be a lot like looking for anything else that's missing.  Take car keys for example.  If mine aren't on the shelf where they belong, I check the other side of the shelf & a couple of coat pockets and usually find them in minutes.

When my wife lost her keys a while back, we had to wait for a snow drift to melt first.  That took a couple of months.

I think you nailed it with "easy", "hazy", and "hard".  A bug is easy to find when you can quickly narrow your search space down to something reasonable.  It's hard when you can't.

All your superiors really need to know is that this is a priority, you're working methodically / you have a search plan, and you're not out of ideas yet.


问:
Separate requests for static and dynamic page content on first page load?
I'm thinking of the following two requests:

Request 1:

Load all static HTML, JavaScript, images, etc. the website framework so to speak. Then fire a second request to get dynamic content (say news items, latest posts).

Request 2

Send new HTML, JavaScript, images, etc. as required by dynamic content.

I'm expecting the first request to be cached for subsequent times a user visits the website, and thus to be a non-issue for returning users. But for first-time users should I maybe build the entire content server-side and send it together in one request? Since in the approach above, both requests need to be responded to in order for the user to be able to use the website.

Can I just leave it as two requests (easier for me to program, since I'm building single page app that relies on Ajax requests)? Or is there an easy way to build everything server side and avoid two requests the for first time users?

... but wouldn't that break the caching mechanism, since the same URL would return partially different content each time?

Is this a known issue with a known solution?

答:
The first approach is the way to go - all links to the site resources are technically individual requests (though with http 1.1 they are made in a single connection with a small keep-alive). So subsequently requesting the dynamic resources is not any different. You might as well embed the link to the dynamic stuff in the html page and just let the browser run.

In addition, caching will apply if you read all resources as normal.


问:
What languages should I know if I'm interested in building web applications?
I'm interested in developing for the web and I'm curious what languages should I know besides html, css, javascript, php/python/ruby. I don't know much about c# or java to make a decision whether to learn them or not, are they used much in the field I'm interested in?
What other technologies should I look into ?</p>

答: If you're looking to do web applications that require many concurrent and/or long polling requests I would say you'd have to look into Erlang and/or Node.js for server side Javascript.</p>

OwnerDisplayName: webguy


问:
Best algorithm to determine whether two arrays can be the same in a circular queue
I'm trying to figure out an efficient way to determine whether two distinct arrays of the same size can be shifted to form the same circular queue. For example:

```<code>Array1 = ['A','B','C','D']
Array2 = ['D','A','B','C']
</code>```

Can form the same circle if both ends are joined together:

I thought that one way would be to loop through one of the arrays while one remains constant, for example:

```<code>while Array1 is not = Array2 and iterations < Length of Array1
      temporary = Array1[last]
      for index is 0, add 1, before index = last
           temporary[index] becomes temporary[index+1]
      Array1[0] = temporary
      if Array1 == Array2 return TRUE
return FALSE
</code>```

Is there a more efficient way? I would need to do this check for several arrays among each other and remove duplicates. Plain speech, pseudocode or Python/C# data structures/code would be appreciated.

答:
This is what I came up with in C#:

```<code>static bool AreArraysCircular(char[] Array1, char[] Array2)
    {
        bool flag = false;
        if (Array1.Length != Array2.Length) return flag; //check the length, if not the same means the arrays are not circular
        int len = Array1.Length;
        int matches = 0; //count for matching characters
        for (int i = 0; i < len * 2; i++)
        {
            if (Array1[matches] == Array2[i % len])
            {
                matches++; //find the next match
                if (matches == len) //already matched whole array
                {
                    flag = true;
                    break;
                }
            }
            else matches = 0; //safeguard probably unnecessary
        }
        return flag;
    }
</code>```

EDIT: Algorithm firstly checks the lengths of both arrays, then it goes through loop double the length of arrays and with index mod length accesses the element in second array and waits for the match. This is using the proposed substring search problem solving.

Body:
This is what I came up with in C#:

static bool AreArraysCircular(char[] Array1, char[] Array2)
    {
        bool flag = false;
        if (Array1.Length != Array2.Length) return flag; //check the length, if not the same means the arrays are not circular
        int len = Array1.Length;
        int matches = 0; //count for matching characters
        for (int i = 0; i < len * 2; i++)
        {
            if (Array1[matches] == Array2[i % len])
            {
                matches++; //find the next match
                if (matches == len) //already matched whole array
                {
                    flag = true;
                    break;
                }
            }
            else matches = 0; //safeguard probably unnecessary
        }
        return flag;
    }

EDIT: Algorithm firstly checks the lengths of both arrays, then it goes through loop double the length of arrays and with index mod length accesses the element in second array and waits for the match. This is using the proposed substring search problem solving.


问:
Use of tenant_id in multi-tenant database
We are building a SASS web application where every company will be using its own database schema. Using postgresql, there is a table 'companies' in the public schema that holds the name of the company and the name of the schema to switch to. In the tenant schema there are a lot of tables that store data specific to this company. Every request, the tenant schema is set based upon the current company as stored in a session.

The internal discussion is this one:

Should the tables in the tenant schema have a company_id column to denote the relation between the data and the company? Or is the current company implied by the used schema, and is it overkill to use the company_id in every table that has a relation with a company?

Opinion 1

The first opinion is that the relations between the company and other tables should be defined explicitly in the table structure. This also enables ActiveRecord queries like: current_company.projects.find(3). Referential integrity is enforced, even for relations that cross the schema boundary.

Opinion 2

The second opinion is that it would be better to drop all company_id columns in all tables because when you switch to a tenant schema, you will never be able to get data from other companies. The same ActiveRecord query must now be written as Project.find(3). The company is implied by the chosen schema, not through a relation. Also, dropping the company_id column from every table would save disk space.

Which approach do you think is best?

答:
A schema in Postgresql is akin to a "database" in, say, MySQL; it is a namespace containing a distinct and separate collection of database objects (tables, views, stored procedures, triggers, etc).  Creating a schema for each tenant will allow you to

Hold a database connection open and switch between schemas,

Query across multiple tenants using UNION, and

Avoid problems where someone changes the ID and accesses the data of some other company.

If you create a schema for each company, you won't need company_id fields in each table; the schema will provide the necessary separation.  Your ActiveRecord query will look something like company.Projects.find(3), where company is the name of the schema corresponding to that particular tenant.


问:
Is turning UI (or other) features on and off based on dates-a code smell?
We have an awful system written in ASP.NET 2.0 that we need to add some functionality to. The problem is that a certain product has UI features that have to be turned on for business initiated after a certain date (and others turned off), while the page has to appear the same for existing business.

I am pushing for a rewrite of the page for new business as I instinctively find the idea of date-based JavaScript UI switches, and the mixing of web controls for the old and new business to be "untidy" (for want of a better word).

Is the practice of having time-based UI features a widely accepted practice, and if not, what are the known risks of pursuing that course of action?

答: This feels like a special case of a more general question: is it a bad practice to disable UI features for specific reasons according to predefined rules?  The answer, then, is "of course not."  Date handing in particular can be tricky because dates and times are difficult, but on general principle there's no good reason to not do it if it's what your business requirements call for.</p>


答:
There's nothing wrong with tweaking a UI based on which features are enabled for a customer, or which deployment types they have chosen, but the change should

depend on meaningful flags, e.g. "HAVE_EXPORT" to enable/disable an exporting option, not on weird date comparisons. The UI has no business knowing the business rule about what was published when, it should fulfill only its UI task and obey UI-specific instructions.

Be controlled server-side, so that a customer cannot surreptitiously enable features for which they haven't paid.

(Note that the opposite - disabling features after a certain time - is a major no-no unless you've clearly communicated that you're selling a time-limited trial version. Creating such time bombs under any other circumstances will make people hate you faster than almost anything else.)

Title: Is turning UI (or other) features on and off based on dates-a code smell?

Body:
We have an awful system written in ASP.NET 2.0 that we need to add some functionality to. The problem is that a certain product has UI features that have to be turned on for business initiated after a certain date (and others turned off), while the page has to appear the same for existing business.

I am pushing for a rewrite of the page for new business as I instinctively find the idea of date-based JavaScript UI switches, and the mixing of web controls for the old and new business to be "untidy" (for want of a better word).

Is the practice of having time-based UI features a widely accepted practice, and if not, what are the known risks of pursuing that course of action?


问:
Name pattern for quickly find descendents with SQL (PATH column with [TopId]...[DirectAncestorId].[OwnId]) NO nested sets
I read a long time ago about a pattern/technique for easily querying for all "descendants" of a record (no need to use CONNECT TO, which is not standard and not available with JPA).

I remembered the pattern being called "nested sets", but now that I am documenting I went to check that and found that "nested sets" is somewhat similar, but not the same.

Typically, it applies to a single table with a 1-N relationship to himself, v.g a table of Person where each record has a Mother attribute that is a foreign key to person.

In order to easily find all of the descendants of a given record, the technique worked like this:

When a record was inserted, the Path attribute would be calculated and stored.

If the record has no "mother", it would be just the record's id followed by a separator (v.g., a dot). So, INSERT INTO PERSON(Id, Name, Mother, Path) VALUES(1, 'Alice' null, '1.').

If the record has a "mother" record, it would prefix the path attribut with the mother path. So, PERSON(Id, Name, Mother, Path) VALUES(2, 'Betty', 1, '1.2.'); and PERSON(Id, 'Carol', Mother, Path) VALUES(3, 2, '1.2.3.');

To search, say, all of Carol descendants (including herself), it becomes as simple as SELECT * FROM Person WHERE Path LIKE '1.%'.

Of course, the cost is that Path is not in a normal form (it is an attribute that does not depend only of its id), so extra care is needed when inserting, deleting or updating records.

Anybody knows the name of this technique? As I said above, I thought it was nested sets but Wikipedia says I am wrong.

答:
I just found it, it is called materialized paths.

A few links referencing/explaining them:

https://stackoverflow.com/questions/2797720/sorting-tree-with-a-materialized-path

https://bojanz.wordpress.com/2014/04/25/storing-hierarchical-data-materialized-path/


问:
What is understood under "unit" in unit testing
As I understand in theory under "unit" people mean method (in OOP). But in practice tests which verify some method in isolation are very fragile behaviour tests (verifying not the result but the fact that some dependency method was called). So I see a lot of people who by unit understand a small set of closely related classes. In this case only outer dependencies are mocked/stubbed and for dependencies which are inside unit real implementations are used. In this case there are more state, meaningful (according to specification) and not so fragile tests. So the question is how do you feel about these approaches and is it valid to call the second approach unit testing or may be it is some kind of low-level integration testing?

If you see some specific considerations about applying TDD by one of these ways of testing, I would be thankful for your thoughts.

答:
My rule of thumb: The smallest unit of code which is still complex enough to contain bugs.

Whether this is a method or class or subsystem depends on the particular code, no general rule can be given.

For example, it does not provide any value to test simple getter/setter methods in isolation, or wrapper methods which only call another method. Even a whole class might be too simple to test, if the class is only a thin wrapper or adapter. If the only thing to test is if a method on a mock is called, then the code under test is to thin.

In other cases a single method might perform some complex calculation which is valuable to test in isolation.

In many cases the complex parts are not individual classes but rather the integration between classes. So you test two or more classes at once. Some will say that this is not unit tests but integration tests, but never mind the terminology: You should test where the complexity is, and these tests should be part of the test suite.


答:
If the changes have to do with some specific business purpose that is date-sensitive, then it's a necessary evil.

If this is about deploying a revision to the program that will change the program permanently, and the old design will never be used again, then it's better to simply deploy an update at the correct time.


答:
Its a requirement, and while it appears to be smelly - basically configuration based on a datetime value - there's no reason time cannot be used to alter your UI. The classic case is a satnav display that changes from bright colours in daytime to a dark theme at night (and if you're really dedicated, a muted colour at in between).

However, one thing I can suggest as an improvement is to remove the concept of a date that enables the controls, but a version number. The version sets the UI configuration (ie you have a flag to say configured for NewCustomer, and in the future can be expanded to cater for the additional controls NewNewCustomer wants, and so on). This is much easier to handle in the code, and smells much nicer.

Then you only have 1 issue which is setting the version number based on some criteria, and this can be done by a date check today, possibly a server-side configuration option later, or even a cookie that is set by user login some time in the future.


答:
The requirement itself isn't problematic, but there are good and bad ways to implement it.  If you have code copied and pasted all over the place that looks like:

```<code>if (businessInitiationDate > cutoffDate)
  enableNewControlsForThisOneLittlePiece();
else
  enableOldControlsForThisOneLittlePiece();
</code>```

That's going to be crazy hard to maintain, even if it seems quicker at the moment.  For example, maybe at some point some older customers will want the new look.  Maybe at some point there will be a third configuration with its own cutoff date.

Ideally, you want this if statement to appear exactly once in your code, preferably on the server side.  However, you also want to avoid just duplicating the entire application and making changes.  Find the common code and factor it out, then create small separate functions for just the parts that are different.  Then enable or disable those functions from one central place.

Body:
The requirement itself isn't problematic, but there are good and bad ways to implement it.  If you have code copied and pasted all over the place that looks like:

if (businessInitiationDate > cutoffDate)
  enableNewControlsForThisOneLittlePiece();
else
  enableOldControlsForThisOneLittlePiece();

That's going to be crazy hard to maintain, even if it seems quicker at the moment.  For example, maybe at some point some older customers will want the new look.  Maybe at some point there will be a third configuration with its own cutoff date.

Ideally, you want this if statement to appear exactly once in your code, preferably on the server side.  However, you also want to avoid just duplicating the entire application and making changes.  Find the common code and factor it out, then create small separate functions for just the parts that are different.  Then enable or disable those functions from one central place.


问:
Difference between PyPy and JVM
From my understanding the default Python interpreter(CPython) compiles source code into bytecode and then interprets the bytecode into machine code. PyPy on the other hand makes use of JIT to optimize often interpreted bytecode into compiled machine code. How is this different then the JVM? The JVM is an interpreter + compiler. It compiles source code to bytecode and then optimizes the often interpreted bytecode into compiled machine code. Is there any other difference?</p>

答:
There are two major differences between the two.

First: the JVM is abstract, PyPy is concrete. The JVM is a specification, a piece of paper. PyPy is an implementation, a piece of code.

There are many different implementations of the JVM which work very differently. Some only interpret the JVM byte code, some only compile it statically ahead-of-time, some only compile it dynamically just-in-time, some have both an interpreter and a JIT compiler, some have an interpreter and multiple JIT compilers, some have no interpreter and only one JIT compiler, some have no interpreter and multiple JIT compilers. Some have tracing JITs, some have method-at-a-time JITs, some have both. Some have native threads, some have green threads. Some have tracing garbage collectors, some have reference counting garbage collectors. And so on and so forth.

Second: PyPy is more general. It is not an implementation of a specific language, it is a framework for easily creating efficient language implementations. There are a lot of different language implementations built using the PyPy framework, there's Topaz (an implementation of Ruby), HippyVM (an implementation of PHP), Pyrolog (Prolog), RSqueak (a Squeak VM), PyGirl (a GameBoy emulator), langjs (JavaScript), and also implementations of Io and Scheme. And of course also an implementation of Python.

Since you asked specifically about the compilers, there is a very important distinction between PyPy's JIT and the JIT compilers of other mixed-mode engines. In a typical mixed-mode engine (e.g. Oracle HotSpot JVM, IBM J9 JVM, Rubinius, Apple Squirrelfish FX, …), the interpreter and the compiler run side-by-side and process the same program. The interpreter starts off, interpreting the program, and once it has been determined that it would be beneficial to compile (parts of) the program, the program gets handed off to the compiler and compiled.

In PyPy, however, the compiler doesn't compile the program that is interpreted by the interpreter. It compiles the interpreter itself as it is interpreting the program!

Now, why would you do something like this? Think about what this means: if you JIT compile the interpreter while it is interpreting the program, what you end up with, is a specialized version of the interpreter which can only interpret that one program, all together compiled to native code. But, an interpreter which can only interpret one single program is indistinguishable from that program. So, in other words, you have just compiled that program without even knowing anything about that program!

This has to do with PyPy being intended as a framework: this way, you only need one JIT compiler and it works for all languages! The only thing you have to write if you want to implement a new language in the PyPy framework, is the interpreter. You get the JIT compiler "for free". And the interpreter can be very simple, it doesn't have to perform any aggressive optimizations or so, because the JIT compiler is quite good. (For example, HippyVM, the PHP implementation using PyPy, is almost 8 times faster than the Zend Engine (the standard PHP implementation) and twice as fast as Facebook's aggressively optimized high-performance PHP implementation HHVM.)

Title: Difference between PyPy and JVM


答:
Sounds fine. It is quite common to have UI's adapt to different users, e.g. here on stackoverflow different features are enabled or disabled based on the karma of an individual user.

The reason you don't like it is that it obviously adds complexity relative to a solution where everybody see the same UI. However the complexity seem to be essential complexity, ie. it a business requirement, not an artifact of a bad architectural decision. Of course it will have a cost (which you should communicate to the business), but if the business decide it is worth the cost, you go ahead an implement it.

Known risks: The biggest risk is probably to get the UI tested in the various configurations. If you start going down the road of enabling/disabling UI features for various groups of users, you can quickly get an explosion of possible configurations.

You should also make sure to implement the restrictions int the business logic layer, so you verify that customers cannot perform operations they are not allowed to, even if the UI should not make it possible in the first place:


答:
Good question, I don't think I have ever sat down and documented the process.

I guess thinking about it now, I just read it:

Line by Line

Of course this doesn't always work, asking the author is usually the last resort.


问:
Is there a hashCode()-like method that can be used for state checking?
I thought up a simple and efficient way to combine states with events to make event handling more efficient. My idea of state checking involves State objects that hold reference to mutable variables in an object.

I figure that using a sort of hashCode() for an Object and checking between the two states would be more efficient than iterating over the contents of a State object and comparing to the target state.

Problem is, hashCode() isn't calculated on a per-state basis. Is there some method similar to hashCode() that I can use to compare two states without comparing their contents directly and is cheap on CPU usage?

Edit: I didn't realize hashCode() is on a per-state basis.

答:
You are looking for hashCode() plus a few of the optimizations and overhead associated with it found in other Java classes.

If the hash code is different, than the state is different. That is part of the contract of hashCode().  However, comparing two hash codes generated on the fly for two objects is just as expensive (and possibly more so because the complete state must be interrogated in order to create the hash code while .equals(T object) can bail out early).

Thus, you go to caching the hash code once you compute it so you only need to generate it once.  However, that 'only generate it once' is 'only generate it once per state'. If the object is an immutable, then you can cache it as soon as it is asked for and return that cached value forever more.  This can be seen in String.hashCode().  String will return the computed hash code if it has already been computed.

However, if the object is mutable, each time you mutate the object you will need to invalidate the hash code that has been generated previously. This is where the overhead comes in.

All that said, the simple and understandable thing to do that doesn't add complexity to your code is to use equals(T object). Test the most likely mutated fields first and let the JIT optimizer do its thing.


问:
OOP design for conditional event processing queue
This will be in C++11, but the object design should be rather agnostic.

I have 3 interface classes, IEvent, ICondition, IRunnable.

The main loop processes multiple kinds of IEvent, ranging from "an Application has launched" to "User clicked position (x,y)". Then for each type of event, a list of IConditionare notified through a listener interface. For example, ConditionUserClickedPos implements IEventClickListener::onClick(int x, int y), which is called by the main loop.

If the position is within the conditions, one or more IRunnable objects are called  through IRunnable::execute(IEvent triggeringEvent), like class RunnableDrawCircleAtClickPosition and class RunnableShowPrettyWindow.

My problem is as follow :

Within IRunnable::execute(IEvent triggeringEvent) implementation, I need to get the precise information of the event, but I don't know the exact class hierarchy of the triggeringEvent.

This can be easily solved with dynamic_cast, checking typeid or other reflective oop methods, but those usually breed rather smelly code. I'm also trying to keep the code extendable for new and unrelated events, conditions and runnables that I don't know about yet.

I could also declare a bunch of overloads for ::execute(...) based on children class types, but this doesn't seem right either.

Is there a silver bullet that I've missed here?

答:
My suggestion is below written in PHP pseudocode. So, we have many types of events, all implementing IAbstractEvent interface. When we need to process an event, we give this event to a factory method FactoryConstructor::constructFactory(). This method creates abstract factory AbstractLoopProcessorFactory descendant for us for processing events of this particular type.

When we have an event which name is DrawCircle, factory method creates DrawCircleLoopProcessorFactory for us. This factory can create concrete DrawCirlceConditionProcessor and DrawCirlceRunnable that can work with IDrawCircleEvent event.

IDrawCircleEvent interface may have an arbitrary number of methods and arbitrary structure. Only it should extend IAbstractEvent to allow our abstract factory to work. So, in DrawCirlceConditionProcessor you already know, that actual event passed to you is IDrawCircleEvent and you can reference it as is.

A type cast is probably required because you have to be able to work with an event queue uniformly. But you trade it for logic separation.

interface IAbstractEvent
{
    public function getName();
}

interface IDrawCircleEvent extends IAbstractEvent
{

}

interface IAbstractConditionProcessor
{
    /**
     * @return bool
     */
    public function check(IAbstractEvent $event);
}

interface IDrawCircleConditionProcessor extends IAbstractConditionProcessor
{

}

interface IAbstractRunnable
{
    /**
     * @param IAbstractEvent $event
     *
     * @return void
     */
    public function process(IAbstractEvent $event);
}

interface IDrawCircleRunnable extends IAbstractRunnable
{

}

abstract class AbstractLoopProcessorFactory
{
    /**
     * @param IAbstractEvent $event
     *
     * @return IAbstractConditionProcessor
     */
    abstract function getConditionProcessor(IAbstractEvent $event);

    /**
     * @param IAbstractEvent $event
     *
     * @return IAbstractRunnable
     */
    abstract function getRunnable(IAbstractEvent $event);
}

class DrawCircleLoopProcessorFactory extends AbstractLoopProcessorFactory
{
    public function getConditionProcessor(IAbstractEvent $event)
    {
        return new DrawCirlceConditionProcessor($event);
    }

    public function getRunnable(IAbstractEvent $event)
    {
        return new DrawCirlceRunnable($event);
    }
}

class FactoryConstructor
{
    /**
     * @param IAbstractEvent $event
     *
     * @return AbstractLoopProcessorFactory
     * @throws Exception
     */
    public static function constructFactory(IAbstractEvent $event)
    {
        switch ($event->getName()) {
            case "DrawCircle":
                return new DrawCircleLoopProcessorFactory();
            default:
                throw new Exception("Unknown event name {$event->getName()}");
        }
    }
}

class Application
{
    public static function main()
    {
        /**
         * @var IAbstractEvent[]
         */
        $eventList = [];

        foreach ($eventList as $event) {
            $factory = FactoryConstructor::constructFactory($event);
            $conditionChecker = $factory->getConditionProcessor();
            if ($conditionChecker->check($event)) {
                $runnable = $factory->getRunnable($event);
                $runnable->process($event);
            }
        }

    }
}
```


答:
What you're describing is the concept of effective dating, which is by no means a novel idea and at its core a type of temporal problem to which you could apply a temporal pattern.

Essentially what you would do in your database is apply an effective date to either form modules or form versions (herein referred to as components), storing some metadata about those components and their effective start/end dates. You'll of course need some data about your users in the application as well.

It sounds like you may have some other more compelling reasons to consider rewriting this application.  If effective dating problems are your only problems, I'd suggest that perhaps implementing effective dating is a better option.  If not, you'll have to evaluate that based on you scenario.


问:
Application development with fully dynamic controls and processes based on database
All software development projects are moving into separation of design, logic , data in patterns like MVC , MVVM and others.

Strangely i got a very strange requirement for a new software; that is :

It is required to have all controls/fields of the screen to be based in the database with their access rules which user is allowed to see which field or control

This is requested so the clients DB Admin be able to remove any field from the screen or change access level(view edit,none) of any field to a user!

I have suggested other ways of maintaining user access and roles, but the client is insisting of having everything each and every single screen control in the database to have full control on the software's screen content by their DB admin.

Is this way of maintaining screen and their content and controls in database has a name or is there a design pattern for that ?!
i know doing the software in this will harm the client but can't provide enough justification for that.

My question is : Is doing software in the described way is recommended or not and why?

答:
The way this is normally done is with user roles and a role access matrix.

Each user has a role, saved in the database along with the user name, password, etc.

Then, there is a two-dimensional role access matrix somewhere, specifying for each role and for each screen field what kind of access is to be had by users who have that specific role on that specific screen field.  The access may be:

"none", meaning that the field should not be shown to users of this role

"read-only", meaning that the field should be displayed, but not be editable, and

"read-write", meaning that the field should be displayed and editable.

In a variation of this scheme, each user can have multiple roles, so the access that a user has to a certain field is computed to be the maximum access permitted by any of the roles held by the user.  When this variation is used, the 'roles' may be called 'groups', in the sense that a user may belong to several groups simultaneously.

In yet another, more sophisticated but even more complicated variation, we introduce permissions as an intermediate step, replacing the role-access matrix with a much smaller role-permission matrix.  In this scenario, each field has a required permission for "read-only" access, and another required permission for "read-write" access. (These required permissions can be hard-coded for each field: they don't need to be configurable.) If a user has a role which has none of the required permissions, the user does not see the field at all.  So, for example, an "email address" field may require some "view sensitive information" permission in order to have "read-only" access to it, and some "edit sensitive information" permission in order to have "read-write" access to it.  Each user has or does not have these permissions depending on their role.  Presumably there will be many fields that will require the same permissions for the same kind of access, so the total number of permissions will be very small, which in turn means that the role-permission matrix will be small.

So, one of these approaches should solve your problem nicely.  In fact, I would be willing to bet that they more closely parallel what your client really wants to accomplish: they probably don't want to tailor the type of access of every single user to every single screen field, they probably have some user groups and possibly some field groups vaguely in mind, and they want different groups of users to have different types of access to different groups of fields.

The role-access matrix or the role-permission matrix can be stored in the database, or they can be stored in an external configuration file, or, if you are building your user interface using some scripting language like PHP, they can even be placed directly in the code, and let the customer modify the PHP source file to alter the permissions.


答:
It's not entirely clear what you're looking for.
But if you want to detect state change events without laborious comparison it's a well proven pattern to use a version indicator. That can be as simple as a counter that is incremented each time any relevant data is modified.

Depending on the purpose you might encounter one of two classes of problems.
First is the AA problem. The set method of property with the value A is called with the value A. A naive implementation records a change (by incrementing the version counter) but nothing actually changed.
Second is the ABA or ABC problem. If a set method is called twice before a 'monitor mechanism' visits the object again it will miss state B and may (in the ABA case) entirely miss that a change 'really' occurred.

That might not matter. It might make the program slightly less efficient (causing say screen updates that in fact change nothing) or worse break logic.

Title: Is there a hashCode()-like method that can be used for state checking?

Body:
I thought up a simple and efficient way to combine states with events to make event handling more efficient. My idea of state checking involves State objects that hold reference to mutable variables in an object.

I figure that using a sort of hashCode() for an Object and checking between the two states would be more efficient than iterating over the contents of a State object and comparing to the target state.

Problem is, hashCode() isn't calculated on a per-state basis. Is there some method similar to hashCode() that I can use to compare two states without comparing their contents directly and is cheap on CPU usage?

Edit: I didn't realize hashCode() is on a per-state basis.


答:
Depending on the severity of the issue and the urgency of fixing it, see if they'll agree to a "time-boxed" effort. Say, two days investigating/trying to re-create the problem. If you don't have it by then, you'll report on what you've eliminated as the problem and see if they want you to keep digging.

For minor issues, they'll likely agree to a short time-box as long as work continues on other issues or features. For major ones, especially those with major visibility, the time-box will let them get regular reports on your effort.


答:
It's a feature toggle with activation based on the date -- which is perfectly valid. Imagine if the feature was only for use during a promotional period, or had to end when a new government regulation kicks in at a certain date.

You're working in APS.NET and JavaScript, but the Java feature-toggle frame work Togglz specifically has a date (and time!) based activation rule.


问:
What stops C from being compiled/interpreted/JIT'ed?
Java is often praised for its amazing portability, which I presume is because of  the JVM. My question is what stops C from being being compiled/interpreted/JIT'ed.., if so, C can also be write once and have it work on what ever device you have. but this is not a popular mechanism for processing a C program.

What are the disadvantages of processing C in this way, also what are the advantages of processing Java in this way and not compiling to machine code, other than the portability of course?

答:
C is what I would call a mid-level language.  Its purpose is to serve as a "very high-level assembler," which is why it works so well as a compiler target, and why it embraces portability so well.

Historically, interpreters have typically been used with high-level languages, in the context of method calls.  In its simplest form, an interpreter merely parses each keyword in the source language along with its associated tokens, and converts that into method calls and parameters.  In practice, what most interpreters do is convert the source language into some intermediate representation, and it is that representation that is interpreted.

What stops C from being interpreted or Jitted?  Nothing.  But that's not C's raison d'être.


答:
Java is highly portable specifically because the language targets the Java Virtual Machine, which, as the name implies, is not a real machine.  Since you can implement a Virtual Machine on the architecture of many different types of real machines, a JVM-based program is highly portable.

C, on the other hand, is specifically designed to be run against real hardware, because it was created for the specific purpose of implementing an operating system, which needs full hardware access.  This means that C code is not particularly portable by design, and when porting a C program from one platform to another, various parts that are specific to the target architecture will need to be rewritten to one degree or another.

Title: What stops C from being compiled/interpreted/JIT'ed?

Body:
Java is often praised for its amazing portability, which I presume is because of  the JVM. My question is what stops C from being being compiled/interpreted/JIT'ed.., if so, C can also be write once and have it work on what ever device you have. but this is not a popular mechanism for processing a C program.

What are the disadvantages of processing C in this way, also what are the advantages of processing Java in this way and not compiling to machine code, other than the portability of course?


答:
There actually are interpreted versions of C, but they are mostly meant to be used for quick experimentation rather than production system.

They are not commonplace, because after all, why would you suffer all the C idiosyncrasies if not to get a small, fast and static executable?


答:
There's some major differences between Java and C.  Java is isolated from the operating system via the java virtual machine (JVM).  The JVM abstracts the operating system away from the program.  A java application might ask the JVM for a chunk of memory, and the JVM then asks the OS for that memory.  There are many JVMs for different platforms / operating systems.  The JVM is what allows the same java program to run on different platforms.

With C, there is no OS isolation.  C programs (usually) run directly on top of the OS, making direct OS calls.  This makes ties that C program to a specific operating system / platform.  Any non-trivial program is going to make calls into the operating system.  In addition, C programs are compiled down into machine code, which is hardware specific.  A compiled C program for x86 cannot be directly run on an ARM processor.


答:
There's really no reason to convert away from degrees.  Just do a simple comparison:

```<code>if abs(lat1 - lat2) < lat_threshold and abs(long1 - long2) < long_threshold:
</code>```

The trick is in setting appropriate thresholds.  This will vary depending on your location, but for your purpose could be considered constant across a metropolitan area, so you can calculate them once manually, or set them empirically.  It also gives you a rectangle instead of a circle, but that's also negligible for your purposes.

Keep in mind if you don't want to deal with estimating velocity and such, you'll need some way of ensuring reports are synchronized in time.

Title: distinguish requests from the same vehicle

Body:
I am implementing an small app to track buses based on Crowdsorcing. The riders send data long, lat, mac, route to the server as JSON string.

In my database I have table bus to insert the transmitted data. One record in the bus table represents one bus vehicle. Therefore, one rider should  update the record of the bus vehicle in the case of many riders are sitting in the same bus and their devices transmit data to the server from the same bus.

To reach that I have tried to filter the requests from the same bus with the aid of the haversine formula but it is overkill for short distance. Is there another way to reach that without taking into consideration the distance between the sender of the requests?

Body:
There's really no reason to convert away from degrees.  Just do a simple comparison:

if abs(lat1 - lat2) < lat_threshold and abs(long1 - long2) < long_threshold:

The trick is in setting appropriate thresholds.  This will vary depending on your location, but for your purpose could be considered constant across a metropolitan area, so you can calculate them once manually, or set them empirically.  It also gives you a rectangle instead of a circle, but that's also negligible for your purposes.

Keep in mind if you don't want to deal with estimating velocity and such, you'll need some way of ensuring reports are synchronized in time.


答:
I suggest giving a range as an estimate.

For example, for easy issues it might be "between 15 minutes and three hours", for hard issues it might be "between two hours and a week".

This should get your point across. If they ask why your best and wost case estimate differ so wildly, you can start explaining the things you mentioned in your question (cyclic process, etc) and even give examples for the best and worst case.


答:
First of all, it's worth noting that Sun's JVM was written in C.  C is a very popular language when portability is needed.

The C language is portable even though many C programs aren't.  This is because C doesn't place as many restrictions on the programmer or make as many assumptions.  If a C programmer wants his programs to be portable, he must put those restrictions upon himself.

In practice, that really isn't much more difficult than living with the restrictions Java forces on you.  It's mostly a matter of being mindful of your endianness and primitive sizes, and using portable libraries like GTK+ instead of platform-specific libraries.

You could make a GTK+ target and C compiler that supported a virtual machine, even probably the JVM, and get existing code to work with very few changes.  In fact, without the garbage collection, a C virtual machine would probably be much simpler.  Why would you want to, though?

The reverse, compiling Java to native code, is likewise doable.  That's basically what the JIT does.  Why would you want to, though?  I'm sure there are pet projects to do it "just because," but they are not in serious use.


答:
My client sells a case management system that works in exactly that way. All accesses to all fields are controllable. It is perfectly usable, although for performance reasons the permissions are cached in the application and updating the database would not have an immediate effect (but a rapid refresh mechanism could be implemented with triggers if required). I am sure there are many other products that work in a similar way.

To make it usable, you would want to structure the field permissions somehow - for example, grouping them into roles, as others have indicated.

Title: Application development with fully dynamic controls and processes based on database

Body:
All software development projects are moving into separation of design, logic , data in patterns like MVC , MVVM and others.

Strangely i got a very strange requirement for a new software; that is :

It is required to have all controls/fields of the screen to be based in the database with their access rules which user is allowed to see which field or control

This is requested so the clients DB Admin be able to remove any field from the screen or change access level(view edit,none) of any field to a user!

I have suggested other ways of maintaining user access and roles, but the client is insisting of having everything each and every single screen control in the database to have full control on the software's screen content by their DB admin.

Is this way of maintaining screen and their content and controls in database has a name or is there a design pattern for that ?!
i know doing the software in this will harm the client but can't provide enough justification for that.

My question is : Is doing software in the described way is recommended or not and why?


答:
Theoretically both C and Java can be both compiled to native code, interpreted, or compiled to a virtual machine.

The technical reason that C is not compiled to a virtual machine, is that there is simply no standard virtual C machine.

And nobody seems to want to define a virtual C machine, or even compile to the Java virtual machine (which is perfectly possible). Probably because nobody who uses C wants to loose its unrivaled speed. Probably also because C is strongest in the open source community that can easily do portability by compilation (distribute and recompile the source and execute), so they do not feel such a need for portability of execution (distribute and execute a binary) as a closed source developer do.


问:
Unit Testing Competition
My employers runs a monthly unit testing day competition. One entire day is dedicated to writing unit tests -- obviously we do more testing throughout the month, but this is an entire day -- and the "winner" of the competition is given a prize.  However, we are finding it's hard to determine who the winner is.

We were assigning points for each test case.  So if you wrote a unit test like this...

```<code>for (int i = 0; i < 100; i++) {
  assertTrue(i*i, square(i));
}
</code>```

you would be given 100 points.  Obviously this is a simplistic example but it demonstrates the problems with assigning "points" to each test case.

We're primarily a Java & Javascript shop.  So I suggested counting number of code branches tested as a metric.  We can easily count the branches tested via a code coverage tool (such as EclEmma).  However, not sure how we would do this with our Selenium tests and getting a code coverage on the Javascript sources (any ideas?)

Does anyone have any suggestions on how we could better determine the winner of this competition?

Edit

I know how to write unit tests, I know how to write effective unit tests, I don't need help determining what to test.  I have no control over this competition -- the competition will go on.  So either I add some input to make it better or carry on gaming the tests (yeah, I game them.  Of course I game them.  There are prizes to be won)

Edit

This question here is obviously not a duplicate, though it contains useful information about how to find good test cases, it does not provide any useful metrics to evaluate the competition.

答:
Does anyone have any suggestions on how we could better determine the winner of this competition?

The only thing which makes sense to me is by voting - every dev can assign some points to every other dev's test (except his own). Maybe 3 points for the test he thinks it is the "most effective" one, 2 points for the second and one to the third. The test with the most points wins. It may give better results when the point assignment is done without knowing beforehand who wrote the particular test.

As a bonus, you will get all your tests peer reviewed.

Title: Unit Testing Competition