问:
Is a finite state machine an appropriate solution for this situation?
I was writing some test code as an example where I had a washing machine class. It has a door state that should be open or closed, and also a running state, either on or off. I want to prevent the running state from changing from 'off' to 'on' when the door is 'open', and also prevent the door from being set to 'open' while the machine is 'on'.

I have this functionality rigged up with a bunch of if statements. It feels inelegant and it could quickly turn into spaghetti code if I want to add another state that puts additional conditions on the changes of other states. I wonder, is a finite state machine a solution for this situation? Would it simplify adding states and defining valid transitions?

答:
You could implement your washing machine as a state machine, but there's just as much potential for state proliferation as there is for if statements if you don't do things carefully.

Working in states requires a different mindset where you think in terms of states (where you are), stimuli (what you get from the outside) and actions (what you do).  In that context, let's look at some things in your model:

A running state, either on or off.

These are your two states, which I'll call WASHING and STOPPED.  I'll add a third called READY_TO_WASH, which is a stopped-but-ready-to-run state you'll see later.

It has a door state that should be open or closed

This isn't really a state, but two stimuli that you get from a sensor on the machine, which I'll call door_opened and door_closed.  Assume that when power is first applied, the washer will detect what state the door is in and send one of those stiumuli.

Prevent the door from being set to 'open' while the machine is 'on'.

This would imply that in addition to the sensor that generates stimuli when the door is opened or closed, there's also a latch that you can program to physically prevent the door from opening.  Let's call the actions that control it door_lock() and door_unlock().

Prevent the running state from changing from 'off' to 'on' when the door is 'open'

Changing between off and on is based a stimulus that comes from the outside, perhaps when the user presses corresponding buttons on the front panel.  Let's call the stimuli we get from those buttons wash_start and wash_stop.

For completeness, let's also say there's a motor in the machine that does the actual washing and is controllable using actions called motor_start() and motor_stop().

Everything above gives us a full set of information about what the washer's states are, what the parts of the washer can be told to do and what stimuli we can get from the outside.  That's enough to build a state machine, which you do by looking at each state and figuring out what to do in response to each stimulus.

The STOPPED state (this is the "ground" state, or the state which the FSM enters when initialized):

On entering this state: Do actions motor_stop() and door_unlock().  This puts the washer into a known, sane state.

On door_open: Do nothing.  We don't care if the door is open when stopped.

On door_closed: transition to the READY_TO_WASH state.

On wash_start:  Do nothing.  The door might be open.  If it's closed, we won't be in this state anyway.

On wash_stop: Do nothing.  We're already stopped.

The READY_TO_WASH state:

On entering this state:  Do actions motor_stop() and door_unlock().  Again, this makes sure the washer is in a sane state.

On door_open: Transition to the STOPPED state.  If the door's open, we're not ready to wash.

On door_closed: Do nothing.  We're already ready and should have been put in this state already.

On wash_start:  Transition to the WASHING state.

On wash_stop: Do nothing.  We're already stopped.

The WASHING state:

On entering this state: Do actions door_lock() and motor_start().

On door_open: Transition to the STOPPED state.  We shouldn't be getting any door stimuli in this state because the latch prevents it.  If the latch fails and someone pulls the door open, this will provide some safety.

On door_closed:  Same as door_open.

On wash_start: Do nothing.  We're already washing.

On wash_stop: Transition to the READY_TO_WASH state.  The door will still be closed, so we're technically ready to wash some more.


问:
Does anyone still use logic analyzers for debugging real time systems?
Many years ago when debugging real time systems (such as the ones used in telephone switches) we had to use logic analyzers (which read execution straight from the CPU) or emulators (which physically replaced the CPU itself).

Is there any situation where this type of instrumenting is still relevant?

答: I still use a four-channel oscilloscope when debugging hardware, but that's just my personal projects. I imagine that people working with microcontrollers in embedded environments still use emulators and logic analyzers, though -- as long as the bus speeds don't get too high, anyway.</p>

ContentLicense: CC BY-SA 3.0


答:
I don't see general-purpose logic analyzers in labs as often as I did ten or twenty years ago.

On the other hand, I see special-purpose logic analyzers far more often.  They're called USB analyzers and VMEbus analyzers, and your managers are INSANE if they put you on such a project without having such an analyzer (and, in the case of VMEbus projects, a chassis slot dedicated to a blank space, to hold the analyzer when (not if, but WHEN) you need it.

I also see far more powerful oscilloscopes a lot more often.  A modern 4-channel digital storage scope is a thing of beauty, and it is absolutely critical if you are doing i2C or SPI or serial or any of a number of other things.

True in-circuit emulators have all but vanished.  JTAG debuggers have become ubiquitous, and they can do ALMOST everything an in-circuit emulator could do.

What I still don't see is adequate attention paid up-front to writing correct source code before ever going into the lab.  Unfortunately, as long as C and C++ are dominant, and Ada is a dirty word, I expect the "code in haste and debug at leisure" mindset to prevail.

Title: Does anyone still use logic analyzers for debugging real time systems?

Body:
Many years ago when debugging real time systems (such as the ones used in telephone switches) we had to use logic analyzers (which read execution straight from the CPU) or emulators (which physically replaced the CPU itself).

Is there any situation where this type of instrumenting is still relevant?


问:
Infinite loop with a singleton - does this type of issue have a name?
I ran into an unusual error while working on my project. To better learn from and remember it, I'd like to know if this type of error has a name or some definition. (The error itself OutOfMemoryError isn't unusual, I'm talking about what lead to this error).

My (simplified) situation was this:

I had a class Singleton:

```<code>class Singleton extends ClassA{
    private static Singleton instance;

    private Singleton(){ // implicitly calls super() }

    public static Singleton getInstance(){
        if (instance==null) instance = new Singleton();
        return instance;
    }
}
</code>```

And it's superclass ClassA:

```<code>abstract class ClassA{
    public ClassA(){
        ClassB objectB = new ClassB();
        // .. some logic ..
    }
}
</code>```

And a class ClassB that uses Singleton in it's constructor:

```<code>class ClassB{
    public ClassB(){
        Singleton singleton = Singleton.getInstance();
        // .. some logic ..
    }
}
</code>```

What happens is the following:

1- ClassB is instantiated somewhere. It's constructor is invoked and calls Singleton.getInstance().

2- Singleton.getInstance() sees that instance == null and executes instance = new Singleton().

3- The constructor of Singleton is run. It's empty, but it implicitly calls the superclass' (ClassA) constructor.

4- The superclass of Singleton instantiates a ClassB object new ClassB().

5- ClassB's constructor is invoked and calls Singleton.getInstance()...

Since the instantiation of instance in Singleton never reached it's finish, instance == null still returns true, and the cycle never ends.

Resulting in an infinite loop, that finally resulted in an OutOfMemoryError.

So my question is: is this kind of infinite-loop-with-singletons error a common issue? Any ideas how I can avoid it in the future?

答:
I can think of a couple of ways to break the cycle.

Don't instantiate a CMajor when instantiating MusicalResources. Let a higher level function construct the necessary Scales. Any time a Scale is constructed, add a reference to MusicalResources.

Don't query MusicalResources for the Notes when constructing an instance of CMajor. Query them on an as needed basis.


问:
Overriding GetHashCode in a mutable struct - What NOT to do?
I am using the XNA Framework to make a learning project. It has a Point struct which exposes an X and Y value; for the purpose of optimization, it breaks the rules for proper struct design, since its a mutable struct.

As Marc Gravell, John Skeet, and Eric Lippert point out in their respective posts about GetHashCode() (which Point overrides), this is a rather bad thing, since if an object's values change while its contained in a hashmap (ie, LINQ queries), it can become "lost".

However, I am making my own Point3D struct, following the design of Point as a guideline. Thus, it too is a mutable struct which overrides GetHashCode(). The only difference is that mine exposes and int for X, Y, and Z values, but is fundamentally the same. The signatures are below:

```<code>public struct Point3D : IEquatable<Point3D>
{
    public int X;
    public int Y;
    public int Z;

    public static bool operator !=(Point3D a, Point3D b) { }
    public static bool operator ==(Point3D a, Point3D b) { }

    public Point3D Zero { get; }

    public override int GetHashCode() { }
    public override bool Equals(object obj) { }
    public bool Equals(Point3D other) { }
    public override string ToString() { }
}
</code>```

I have tried to break my struct in the way they describe, namely by storing it in a List<Point3D>, as well as changing the value via a method using ref, but I did not encounter they behavior they warn about (maybe a pointer might allow me to break it?).

Am I being too cautious in my approach, or should I be okay to use it as is?

答:
Let's break it down.

Is a mutable struct with public fields a good idea?

No. You already know that it is not, but you're choosing to play with fire while walking on thin ice anyways. I would advise against using Point as a model. Value types should logically be values, and values don't change, variables change.

That said, there can be good performance reasons for doing what you're doing; I would only do so if I had clear empirical evidence that there was no other way to meet my performance goals.

If I put a mutable struct into a dictionary and then mutate it, can the struct be "lost" in the hash code?

The question is not answerable because it presumes a falsehood. You can't put a mutable struct into a dictionary and then mutate it. Asking "what happens when I do something impossible?" doesn't afford answers upon which you can make engineering decisions.

What happens when I try to mutate a mutable struct that I've put into a dictionary?

Value types are copied by value; that's why they're called "value types". When you fetch the value from the dictionary, you make a copy. If you then mutate it, you mutate the copy. If you try to mutate it directly by changing a field, the compiler will tell you that you are mutating a copy and that the mutation will be lost.

So what's the real danger of putting a mutable struct into a dictionary?

The danger of putting a mutable value type in a dictionary is that mutations are lost, not that the object gets lost in the dictionary. That is, when you say:

```<code>struct Counter
{
  public int x;
  public void Increment() { x = x + 1; }
  ...
}

...

var c = new Counter();
var d = new Dictionary<string, Counter>();
d["hello"] = c;
c.Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);
d["hello"].Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);
</code>```

then the increment to c is preserved but not copied to the dictionary, and the increment of the dictionary's copy is lost because it is made to a copy, not to the dictionary.

This is very confusing for people, which is why you should avoid it.

Body:
Let's break it down.

Is a mutable struct with public fields a good idea?

No. You already know that it is not, but you're choosing to play with fire while walking on thin ice anyways. I would advise against using Point as a model. Value types should logically be values, and values don't change, variables change.

That said, there can be good performance reasons for doing what you're doing; I would only do so if I had clear empirical evidence that there was no other way to meet my performance goals.

If I put a mutable struct into a dictionary and then mutate it, can the struct be "lost" in the hash code?

The question is not answerable because it presumes a falsehood. You can't put a mutable struct into a dictionary and then mutate it. Asking "what happens when I do something impossible?" doesn't afford answers upon which you can make engineering decisions.

What happens when I try to mutate a mutable struct that I've put into a dictionary?

Value types are copied by value; that's why they're called "value types". When you fetch the value from the dictionary, you make a copy. If you then mutate it, you mutate the copy. If you try to mutate it directly by changing a field, the compiler will tell you that you are mutating a copy and that the mutation will be lost.

So what's the real danger of putting a mutable struct into a dictionary?

The danger of putting a mutable value type in a dictionary is that mutations are lost, not that the object gets lost in the dictionary. That is, when you say:

struct Counter
{
  public int x;
  public void Increment() { x = x + 1; }
  ...
}

...

var c = new Counter();
var d = new Dictionary<string, Counter>();
d["hello"] = c;
c.Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);
d["hello"].Increment();
Console.WriteLine(c.x);
Console.WriteLine(d["hello"].x);

then the increment to c is preserved but not copied to the dictionary, and the increment of the dictionary's copy is lost because it is made to a copy, not to the dictionary.

This is very confusing for people, which is why you should avoid it.


答:
One of the downsides of Singletons is how they interact with super and sub classes. Another downside of Singletons is nesting them -- that gets messy fast. No offense, but I find it a little funny when you say, "I don't see the problem..." when in fact you are seeing a problem that blows up your runtime engine ;)

Aside from that, your model is all kitty-wampus. Again, no offense, but...! I think, for example, you're making an equivalence between a Scale and a Note that messes up the hierarchy. I'd take out the Singleton code first, and then step back and make a diagram of the is-a and has-a relationships (for example, it might be cleaner if Scale "has a" Note instead of "is a" Note)

It might be good to diagram it out, with the classes, subclasses, and instances laid out with arrows between them.

If you're dishing out immutable reference objects, bundling them up as public static final members of some container class is a lot cleaner and less nastiness-prone than Singleton. Also, I'm not sure where, but I think that enums are going to be your friends here too.

(Enums are kind of the Java-approved version of immutable Singleton, again without the nastiness.)

Title: Infinite loop with a singleton - does this type of issue have a name?

Body:
I ran into an unusual error while working on my project. To better learn from and remember it, I'd like to know if this type of error has a name or some definition. (The error itself OutOfMemoryError isn't unusual, I'm talking about what lead to this error).

My (simplified) situation was this:

I had a class Singleton:

```<code>class Singleton extends ClassA{
    private static Singleton instance;

    private Singleton(){ // implicitly calls super() }

    public static Singleton getInstance(){
        if (instance==null) instance = new Singleton();
        return instance;
    }
}
</code>```

And it's superclass ClassA:

```<code>abstract class ClassA{
    public ClassA(){
        ClassB objectB = new ClassB();
        // .. some logic ..
    }
}
</code>```

And a class ClassB that uses Singleton in it's constructor:

```<code>class ClassB{
    public ClassB(){
        Singleton singleton = Singleton.getInstance();
        // .. some logic ..
    }
}
</code>```

What happens is the following:

1- ClassB is instantiated somewhere. It's constructor is invoked and calls Singleton.getInstance().

2- Singleton.getInstance() sees that instance == null and executes instance = new Singleton().

3- The constructor of Singleton is run. It's empty, but it implicitly calls the superclass' (ClassA) constructor.

4- The superclass of Singleton instantiates a ClassB object new ClassB().

5- ClassB's constructor is invoked and calls Singleton.getInstance()...

Since the instantiation of instance in Singleton never reached it's finish, instance == null still returns true, and the cycle never ends.

Resulting in an infinite loop, that finally resulted in an OutOfMemoryError.

So my question is: is this kind of infinite-loop-with-singletons error a common issue? Any ideas how I can avoid it in the future?


问:
POST and PUT requests – is it just the convention?
I've read quite a few articles on the difference between POST and PUT and in when the two should be used. But there are still few things confusing me ( hopefully questions will make some sense ):

1) We should use PUT to create resources when we want clients to specify the URI of the newly created resources and we should use POST to create resources when we let service generate the URI of the newly created resources.

a) Is it just by convention that POST create request doesn't contain an URI of the newly created resource or POST create request actually can't contain the URI of the newly created resource?

b) PUT has idempotent semantics and thus can be safely used for absolute updates ( ie we send entire state of the resource to the server ), but not also for relative updates ( ie we send just changes to the resource state ), since that would violate its semantics.

But I assume it's still possible for PUT to send relative updates to the server, it's just that in that case the PUT update won't be idempotent?

2) I've read somewhere that we should "use POST to append a resource to a collection identified by a service-generated URI".

a) What exactly does that mean? That if URIs for the resources were generated by a server ( thus the resources were created via POST ), then ALL subsequent resources should also be created via POST? Thus, in such situation no resource should be created via PUT?

b) If my assumption under a) is correct, could you elaborate why we shouldn't create some resources via POST and some via PUT ( assuming server already contains a collection of resources created via POST )?

答:
I asked a nearly identical question here

Spring REST follows your model (PUT = client supplied resource id). But they admit that it was a serious debate. Referring to the spec isn't good enough. It just isn't clear on this issue (or at least, clear enough).

As for partial updates, my understanding is that, for those, you would use the PATCH command


问:
Significant amount of the time, I can't think of a reason to have an object instead of a static class. Do objects have more benefits than I think?
I understand the concept of an object, and as a Java programmer I feel the OO paradigm comes rather naturally to me in practice.

However recently I found myself thinking:

Wait a second, what are actually the practical benefits of using an object over using a static class (with proper encapsulation and OO practices)?

I could think of two benefits of using an object (both are significant and powerful):

Polymorphism: allows you to swap functionality dynamically and
flexibly during runtime. Also allows to add new functionality
'parts' and alternatives to the system easily. For example if
there's a Car class designed to work with Engine objects, and you
want to add a new Engine to the system that the Car can use, you can create a new
Engine subclass and simply pass an object of this class into the
Car object, without having to change anything about Car. And you can decide to do so during runtime.

Being able to 'pass functionality around': you can pass an object
around the system dynamically.

But are there any more advantages to objects over static classes?

Often when I add new 'parts' to a system, I do so by creating a new class and instantiating objects from it.

But recently when I stopped and thought about it, I realized that a static class would do just the same as an object, in a lot of the places where I normally use an object.

For example, I'm working on adding a save/load-file mechanism to my app.

With an object, the calling line of code will look like this: Thing thing = fileLoader.load(file);

With a static class, it would look like this: Thing thing = FileLoader.load(file);

What's the difference?

Fairly often I just can't think of a reason to instantiate an object when a plain-old static-class would act just the same. But in OO systems, static classes are fairly rare. So I must be missing something.

Are there any more advantages to objects other from the two that I listed? Please explain.

EDIT: To clarify. I do find objects very useful when swapping functionality, or passing data around. For example I wrote an app that makes up melodies. MelodyGenerator had several subclasses that create melodies differently, and objects of these classes were interchangable (Strategy pattern).

The melodies were objects too, since it's useful to pass them around. So were the Chords and Scales.

But what about 'static' parts of the system - that aren't going to be passed around? For example - a 'save file' mechanism. Why should I implement it in an object, and not a static class?

答:
lol you sound like a team that I used to work on ;)

Java (and probably C#) certainly supports that programming style. And I work with people who's first instinct is, "I can make that a static method!" But there are some subtle costs that catch up with you over time.

1) Java is an Object Oriented language. And it drives the functional guys nuts, but really it holds up pretty well. The idea behind OO is bundling functionality with state to have small units of data and functionality that preserve their semantics by hiding state and exposing only the functions that make sense in that context.

By moving to a class with only static methods, you're breaking the "state" part of the equation. But the state still has to live somewhere. So what I've seen over time is that a class with all static methods begins to have more and more complicated parameter lists, because the state is moving from the class and into the function calls.

After you make a class with all static methods, run through and just survey how many of those methods have a single, common parameter. It's a hint that that parameter should either be the containing class for those functions, or else that parameter should be an attribute of an instance.

2) The rules for OO are pretty well understood. After a while, you can look at a class design and see if it meets criteria like SOLID. And after lots of practice unit testing, you develop a good sense of what makes a class "right-sized" and "coherent". But there aren't good rules for a class with all static methods, and no real reason why you shouldn't just bundle up everything in there. The class is open in your editor, so what the heck? Just add your new method there. After a while, your application turns into a number of competing "God Objects", each trying to dominate the world. Again, refactoring them into smaller units is highly subjective and hard to tell if you've got it right.

3) Interfaces are one of the most powerful features of Java. Class inheritance has proven to be problematic, but programming with interfaces remains one of the most powerful tricks of the language. (ditto C#) All-static classes can't put themselves into that model.

4) It slams the door on important OO techniques that you can't take advantage of. So you may work for years with only a hammer in your toolbox, without realizing how much easier things would have been if you'd had a screwdriver, too.

4.5) It creates the hardest, most unbreakable compile-time dependencies possible. So, for example if you have FileSystem.saveFile() then there is no way of changing that, short of faking out your JVM at run time. Which means that every class that references your static function class has a hard, compile-time dependency on that specific implementation, which makes extension almost impossible, and complicates testing tremendously. You can test the static class in isolation, but it becomes very difficult to test the classes that refer to that class in isolation.

5) You'll drive your co-workers crazy. Most of the professionals I work with take their code seriously, and pay attention to at least some level of design principles. Setting aside the core intent of a language will have them pulling their hair out because they'll be constantly refactoring the code.

When I'm in a language, I always try to use a language well. So, for example, when I'm in Java, I use good OO design, because then I'm really leveraging the language for what it does. When I'm in Python, I mix module-level functions with occasional classes -- I could only write classes in Python, but then I think I wouldn't be using the language for what it's good at.

Another tactic is to use a language badly, and them complain about all the problems its causing. But that applies to pretty much any technology.

The key feature of Java is managing complexity in small, testable units that hang together so they're easy to understand. Java emphasizes clear interface definitions independent of the implementation -- which is a huge benefit. That's why it (and other similar OO languages) remain so widely used. For all the verbosity and ritualism, when I'm done with a big Java app, I always feel like the ideas are more cleanly separated in code than my projects in a more dynamic language.

It's a hard one, though. I've seen people get the "all static" bug, and it's kind of hard to talk them out of it. But I've seen them have a big sense of relief when they get over it.


答:
It depends on the language and the context, sometimes. For example, PHP scripts used for servicing requests always have one request to service and one response to generate throughout the entire lifetime of the script, so static methods to act on the request and generate a response may be appropriate. But in a server written on Node.js, there may be many different requests and responses all at the same time. So the first question is -- are you sure that the static class really corresponds to a singleton object?

Secondly, even if you have singletons, using objects allows you to take advantage of polymorphism using techniques like Dependency_injection and Factory_method_pattern . This is often used in various Inversion_of_control patterns, and useful for creating mock objects for testing, logging, etc.

You mentioned the advantages above, so here is one you didn't: inheritance. Many languages have no ability to override static methods the same way that instance methods can be overridden. In general, it's much harder to inherit and override static methods.

Title: Significant amount of the time, I can't think of a reason to have an object instead of a static class. Do objects have more benefits than I think?

Body:
I understand the concept of an object, and as a Java programmer I feel the OO paradigm comes rather naturally to me in practice.

However recently I found myself thinking:

Wait a second, what are actually the practical benefits of using an object over using a static class (with proper encapsulation and OO practices)?

I could think of two benefits of using an object (both are significant and powerful):

Polymorphism: allows you to swap functionality dynamically and
flexibly during runtime. Also allows to add new functionality
'parts' and alternatives to the system easily. For example if
there's a Car class designed to work with Engine objects, and you
want to add a new Engine to the system that the Car can use, you can create a new
Engine subclass and simply pass an object of this class into the
Car object, without having to change anything about Car. And you can decide to do so during runtime.

Being able to 'pass functionality around': you can pass an object
around the system dynamically.

But are there any more advantages to objects over static classes?

Often when I add new 'parts' to a system, I do so by creating a new class and instantiating objects from it.

But recently when I stopped and thought about it, I realized that a static class would do just the same as an object, in a lot of the places where I normally use an object.

For example, I'm working on adding a save/load-file mechanism to my app.

With an object, the calling line of code will look like this: Thing thing = fileLoader.load(file);

With a static class, it would look like this: Thing thing = FileLoader.load(file);

What's the difference?

Fairly often I just can't think of a reason to instantiate an object when a plain-old static-class would act just the same. But in OO systems, static classes are fairly rare. So I must be missing something.

Are there any more advantages to objects other from the two that I listed? Please explain.

EDIT: To clarify. I do find objects very useful when swapping functionality, or passing data around. For example I wrote an app that makes up melodies. MelodyGenerator had several subclasses that create melodies differently, and objects of these classes were interchangable (Strategy pattern).

The melodies were objects too, since it's useful to pass them around. So were the Chords and Scales.

But what about 'static' parts of the system - that aren't going to be passed around? For example - a 'save file' mechanism. Why should I implement it in an object, and not a static class?


问:
Should sanity be a property of a programmer or a program?
I design and implement languages, that can range from object notations to markup languages. In many cases I have considered restrictions in favor of sanity (common knowledge), like in the case of control characters in identifiers. There are two consequences to consider before doing this:

It takes extra computation

It narrows liberty

I'm interested to learn how developers think of decisions like this. As you may know Microsoft C# is very open on the contrary. If you really want to prefix your integer as Long with 'l' instead of 'L' and so risk other developers of confusing '1' and 'l', no problem. If you want to name your variables in non-latin script so they will contrast with C#'s latin keywords, no problem. Or if you want to distribute a string over multiple lines and so break a series of indentation, no problem.

It is cheap to ensure consistency with restrictions and this makes it tempting to implement. But in the case of disallowing non-latin characters (concerning the second example), it means a discredit to Unicode, because one would not take full advantage of its capacity.

答:
The primary goals in a language should be:

Allow a programmer to actually express what he wants.  For example, rather than having a small number of integer types, allow a programmer to specify which characteristics are important, including representable range, wrapping behavior, overflow trapping, endianness, etc.  Don't force programmers to specify properties which aren't of interest, but allow specification of whatever combination of properties is important.  For floating-point types, allow code some control over precision/speed trade-offs.  Allow types to propagate into expressions, so that e.g. long1 = int1 + int2; will perform the arithmetic as long.(*)

Require "yes that's what I mean" markers in places where there's more than one thing a programmer might plausibly have intended, but not in cases where there the straightforward meaning is the only one that makes sense.  An initialization like double someDouble = 0.1f; might match programmer intention, but is more likely a mistake; it would be appropriate to require something like double someDouble = FloatToDouble(0.1f;.  On the other hand, float someFloat = 0.1; would only have one plausible meaning, and should thus store the fraction 1/10 into someFloat as accurately as possible.

Allow programmers to specify places when implicit conversions should be applied more strictly than usual, and places where they should be applied more loosely.  For example, if a language supports auto-boxing, allow a means by which a method parameter can say that it should not accept an implicitly-auto-boxed object.

When deciding what kinds of implicit constructs should or should not be legal, think about the effects of changes to parts of the code.  For example, if code is required to say someField = (float)Math.Sqrt(something) rather than simply someField = Math.Sqrt(something) when someField is a float, how will that affect the effort required to make someFloat be a double if float precision is found to be inadequate?

(*) The normal argument I've read against allowing types to propagate into expressions is that it leads to ambiguous situations involving operator overloads.  To that I would suggest allowing methods to either specify which overloads to favor in cases of ambiguity, or require that the invoking code make clear what it wants.  Further, given an integer expression like (a*b+c)/d, I would suggest that requiring an indication of how the dividend should be computed would make programmer intentions clearer than would applying a default behavior.


答:
It depends entirely on the philosophy of the language.

C allows you to deliberately shoot yourself in the foot, in order to obtain the best possible performance.  C++ allows you to blow your leg off.  Java is a bondage and discipline language, preferring ceremony and safety over performance.  Haskell's type system emphasizes mathematical proof of consistency.

Title: Should sanity be a property of a programmer or a program?

Body:
I design and implement languages, that can range from object notations to markup languages. In many cases I have considered restrictions in favor of sanity (common knowledge), like in the case of control characters in identifiers. There are two consequences to consider before doing this:

It takes extra computation

It narrows liberty

I'm interested to learn how developers think of decisions like this. As you may know Microsoft C# is very open on the contrary. If you really want to prefix your integer as Long with 'l' instead of 'L' and so risk other developers of confusing '1' and 'l', no problem. If you want to name your variables in non-latin script so they will contrast with C#'s latin keywords, no problem. Or if you want to distribute a string over multiple lines and so break a series of indentation, no problem.

It is cheap to ensure consistency with restrictions and this makes it tempting to implement. But in the case of disallowing non-latin characters (concerning the second example), it means a discredit to Unicode, because one would not take full advantage of its capacity.


问:
Storing editable site content?
We have a Django-based website for which we wanted to make some of the content (text, and business logic such as pricing plans) easily editable in-house, and so we decided to store it outside the codebase. Usually the reason is one of the following:

It's something that non-technical people want to edit. One example is copywriting for a website - the programmers prepare a template with text that defaults to "Lorem ipsum...", and the real content is inserted later to the database.

It's something that we want to be able to change quickly, without the need to deploy new code (which we currently do twice a week). An example would be features currently available to the customers at different tiers of pricing. Instead of hardcoding these, we read them from database.

The described solution is flexible but there are some reasons why I don't like it.

Because the content has to be read from the database, there is a performance overhead.

We mitigate that by using a caching scheme, but this also adds some complexity to the system.

Developers who run the code locally see the system in a significantly different state compared to how it runs on production. Automated tests also exercise the system in a different state. Situations like testing new features on a staging server also get trickier - if the staging server doesn't have a recent copy of the database, it can be unexpectedly different from production.

We could mitigate that by committing the new state to the repository occasionally (e.g. by adding data migrations), but it seems like a wrong approach. Is it?

Any ideas how best to solve these problems? Is there a better approach for handling the content that I'm overlooking?

答:
Any ideas how best to solve these problems?

We had the very same situation. We ended up using the following Django apps:

I18N flavor of flatpages

with the Redactor WYSIWYG editor enabled.

It's not perfect, but it gives you all you need:

non-technical people can edit,

no code deployment needed.

If you need version control, the reversion app will give you just that.

To have developers experience the same pages as on the production system, if that's an actual requirement, export from production to development and test by using fixtures.

Is there a better approach for handling the content that I'm overlooking?

Conceptually, I think you are on the right track. Ask yourself if you need to implement your own solution, or if you can live with some sort of CMS. Flatpages is one very simple version of that. More sophisticated CMS are available.

Title: Storing editable site content?


答:
In addition to Rob Y's post

As long as the functionality of your load(File file) can be clearly seperated from all the other functions that you use, it is fine to use a static method/class. You externalize the state (what is not a bad thing) and you also don't get redundancy as you can for example partial apply or curry your function so that you don't have to repeat yourself. (that is actually the same or similar to using a factory pattern)

However, as soon as two of these functions start to have a common use you want to be able to somehow group them. Imagine you not only have a load function but also a hasValidSyntax function. What will you do?

```<code>     if (FileLoader.hasValidSyntax(myfile))
          Thing thing = FileLoader.load(myfile);
     else
          println "oh noes!"
</code>```

See the two references to myfile here? You start to repeat yourself because your externalized state has to be passed for every call. Rob Y has described how you internalize the state (here the file) so that you can do it like this:

```<code>     FileLoader myfileLoader = new FileLoader(myfile)
     if (myfileLoader.hasValidSyntax())
          Thing thing = myfileLoader.load();
     else
          println "oh noes!"
</code>```

Body:
In addition to Rob Y's post

As long as the functionality of your load(File file) can be clearly seperated from all the other functions that you use, it is fine to use a static method/class. You externalize the state (what is not a bad thing) and you also don't get redundancy as you can for example partial apply or curry your function so that you don't have to repeat yourself. (that is actually the same or similar to using a factory pattern)

However, as soon as two of these functions start to have a common use you want to be able to somehow group them. Imagine you not only have a load function but also a hasValidSyntax function. What will you do?

     if (FileLoader.hasValidSyntax(myfile))
          Thing thing = FileLoader.load(myfile);
     else
          println "oh noes!"

See the two references to myfile here? You start to repeat yourself because your externalized state has to be passed for every call. Rob Y has described how you internalize the state (here the file) so that you can do it like this:

     FileLoader myfileLoader = new FileLoader(myfile)
     if (myfileLoader.hasValidSyntax())
          Thing thing = myfileLoader.load();
     else
          println "oh noes!"


问:
Where does Rails get its datetime for creating records?
I have a rails app with a data model called 'jobs' and I'm faced with a critical design choice crossroads.

I don't know enough about Rails and its inner workings to be able to say for sure what I should do despite a complete read of the rails and ruby docs.

I want to be able to accurately display the age of a job record in days. So when a customer logs in, they can see that the job they submitted is 'x' days old.

Where does a rails app on Heroku get its time stamps? From Heroku? Or the customers system clock?

If a customer has a out of date system clock and submits a job, it could really mess up the sorting of their job list, not to mention me the overseer of job records.

Any advice out there?

EDIT: Just to be clear, i'm not asking how to list jobs by their date, but to which clock does a rails app on Heroku base it's records.

答:
The touch method updates the updated_at field and save the record. Looking at it's source code we can see it takes the timestamp from current_time_from_proper_timezone. Looking at it's source code we can see it uses a Time.now to fetch the time. Time.now is an alias to Time.new, which creates a Time object that according to the documentation "is initialized to the current system time if no argument is given".

Since all that runs on the server, it uses the local time of the server. So as long as you don't use JavaScript on the clients machines to calculate the durations, they should be accurate.


答:
You need to consider the distinction between standards/specifications vs. guidelines.

Standards/Specifications:

Conformance to specifications is expected and assumed by most browsers and other clients. They handle requests assuming that the spec holds true. Some of these "rules" are specified here: Hypertext Transfer Protocol. The HTTP specification goes into more detail - recommended reading for anyone doing web development.

For example, for the HTTP specification, browsers assume that GET would have no side effects, and so cache most GET requests to save bandwidth and server calls. PUT is meant to be idempotent, so browsers are allowed to repeat PUT calls without any confirmation from end-users (not so for POST).

Not following these standards is of course possible, but you may break the behavior of compliant clients and possibly cause hard-to-track bugs.

Guidelines/Conventions:

The other part that you mention are guidelines. They are used for uniformity and to make sure that other people can understand/follow your API easily. The mapping of CRUD to REST calls that you mention, is one such guideline. It does not address all scenarios, can sometimes be bad design, but is still a useful abstraction if used judiciously.

So the typical mapping is as follows:

GET is an idempotent method which should not take an input payload, only query params. Hence it is usually used for queries and read operations on the server.

PUT is also idempotent, but can take a payload body. Hence, its semantics are used for doing a full replace/update of a resource. If you repeat the call, there is no change because it is a full replace anyway. PUT can also be mapped to a create where the client specified the id of the new resource. For example, you can PUT to the following address with the user's details in the body:

```<code>PUT http://www.example.com/users/<new_user_id>
{
    ...
}
</code>```

This should still be implemented as idempotent - a repeated call would create the same user with the same id, essentially no effective change.

PATCH is a new addition to the HTTP spec. It can be used to send partial changes and merge them on the server. This does not have widespread adoption yet but should be the way going ahead.

POST is more of a generic "everything else" method. It has no restrictions such as being idempotent. In many cases, it is mapped to sub-resource creation. For example, you could POST a user's details to the following URL to have a new user created for you:

```<code>POST http://www.example.com/users
{
    ...
}
</code>```

The convention is that the server creates the user id and returns it to you. Later, you can access the created user with:

```<code>GET http://www.example.com/users/<created_user_id>
</code>```

Title: POST and PUT requests – is it just the convention?

Body:
I've read quite a few articles on the difference between POST and PUT and in when the two should be used. But there are still few things confusing me ( hopefully questions will make some sense ):

1) We should use PUT to create resources when we want clients to specify the URI of the newly created resources and we should use POST to create resources when we let service generate the URI of the newly created resources.

a) Is it just by convention that POST create request doesn't contain an URI of the newly created resource or POST create request actually can't contain the URI of the newly created resource?

b) PUT has idempotent semantics and thus can be safely used for absolute updates ( ie we send entire state of the resource to the server ), but not also for relative updates ( ie we send just changes to the resource state ), since that would violate its semantics.

But I assume it's still possible for PUT to send relative updates to the server, it's just that in that case the PUT update won't be idempotent?

2) I've read somewhere that we should "use POST to append a resource to a collection identified by a service-generated URI".

a) What exactly does that mean? That if URIs for the resources were generated by a server ( thus the resources were created via POST ), then ALL subsequent resources should also be created via POST? Thus, in such situation no resource should be created via PUT?

b) If my assumption under a) is correct, could you elaborate why we shouldn't create some resources via POST and some via PUT ( assuming server already contains a collection of resources created via POST )?

Body:
You need to consider the distinction between standards/specifications vs. guidelines.

Standards/Specifications:

Conformance to specifications is expected and assumed by most browsers and other clients. They handle requests assuming that the spec holds true. Some of these "rules" are specified here: Hypertext Transfer Protocol. The HTTP specification goes into more detail - recommended reading for anyone doing web development.

For example, for the HTTP specification, browsers assume that GET would have no side effects, and so cache most GET requests to save bandwidth and server calls. PUT is meant to be idempotent, so browsers are allowed to repeat PUT calls without any confirmation from end-users (not so for POST).

Not following these standards is of course possible, but you may break the behavior of compliant clients and possibly cause hard-to-track bugs.

Guidelines/Conventions:

The other part that you mention are guidelines. They are used for uniformity and to make sure that other people can understand/follow your API easily. The mapping of CRUD to REST calls that you mention, is one such guideline. It does not address all scenarios, can sometimes be bad design, but is still a useful abstraction if used judiciously.

So the typical mapping is as follows:

GET is an idempotent method which should not take an input payload, only query params. Hence it is usually used for queries and read operations on the server.

PUT is also idempotent, but can take a payload body. Hence, its semantics are used for doing a full replace/update of a resource. If you repeat the call, there is no change because it is a full replace anyway. PUT can also be mapped to a create where the client specified the id of the new resource. For example, you can PUT to the following address with the user's details in the body:

PUT http://www.example.com/users/<new_user_id>
{
    ...
}

This should still be implemented as idempotent - a repeated call would create the same user with the same id, essentially no effective change.

PATCH is a new addition to the HTTP spec. It can be used to send partial changes and merge them on the server. This does not have widespread adoption yet but should be the way going ahead.

POST is more of a generic "everything else" method. It has no restrictions such as being idempotent. In many cases, it is mapped to sub-resource creation. For example, you could POST a user's details to the following URL to have a new user created for you:

POST http://www.example.com/users
{
    ...
}

The convention is that the server creates the user id and returns it to you. Later, you can access the created user with:

GET http://www.example.com/users/<created_user_id>


问:
Are super methods in JavaScript limited to functional inheritance, as per Crockford's book?
In Douglas Crockford's "JavaScript: The Good Parts", he walks through three types of inheritance: classical, prototypal, and functional. In the part on functional inheritance he writes:

"The functional pattern also gives us a way to deal with super methods."

He then goes on to implement a method named "superior" on all Objects. However, in the way he uses the superior method, it just looks like he is copying the method on the super object for later use:

```<code>// crockford's code:
var coolcat = function(spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};
</code>```

The original get_name method is copied to super_get_name. I don't get what's so special about functional inheritance that makes this possible. Can't you do this with classical or prototypal inheritance? What's the difference between the code above and the code below:

```<code>var CoolCat = function(name) {
    this.name = name;
}

CoolCat.prototype = new Cat();

CoolCat.prototype.super_get_name = CoolCat.prototype.get_name;
CoolCat.prototype.get_name = function (n) {
    return 'like ' + this.super_get_name() + ' baby';
};
</code>```

Doesn't this second example provide access to "super methods" too?

答:
It's a great question about a great book. The book takes a couple of readings to be fully digested. I came across this question, while researching some subtleties of javascript based on the book. I've basically had the same question, but after some pondering, I think that both kindohm's own and Raynos answers are incomplete.

I think kindohm is right that the reason is related to privacy and access, but it is not because the super method is private with the functional approach, as Raynos rightly points out.

On the other hand Raynos's answer sounds almost like there is a mistake in the book, as Raynos offers a different solution than the one that the book gives.

But I think that the solution given in the book still has its place. I think that the main reason/justification for it is in the paragraph preceding the code for the 'superior' method:

The function will invoke the original method even if the property is
  changed

This is the difference between the functional approach and the pseudo-classical approach that is given as an example in the original question.

It is not a perfect privacy but it gives an additional layer of isolation.


答:
Just my two cents.

For your question:

But what about 'static' parts of the system - that aren't going to be passed around? For example - a 'save file' mechanism. Why should I implement it in an object, and not a static class?

You can ask yourself if the mechanism of the part of the system that plays sounds, or the part of the system that saves data to a file WILL CHANGE. If your answer is yes, that indicate that you should abstract them using abstract class / interface. You may ask, how can I know the future things? Definitely, we cann't. So, if the thing is stateless, you can use 'static class' such as java.lang.Math, otherwise, use object-oriented approach.


问:
Tail-recursive implementation of take-while
I am trying to write a tail-recursive implementation of the function take-while in Scheme (but this exercise can be done in another language as well). My first attempt was

```<code>(define (take-while p xs)
  (if (or (null? xs)
          (not (p (car xs))))
      '()
      (cons (car xs) (take-while p (cdr xs)))))
</code>```

which works correctly but is not tail-recursive. My next attempt was

```<code>(define (take-while-tr p xs)
  (let loop ((acc '())
             (ys xs))
    (if (or (null? ys)
            (not (p (car ys))))
        (reverse acc)
        (loop (cons (car ys) acc) (cdr ys)))))
</code>```

which is tail recursive but needs a call to reverse as a last step in order to return the result list in the proper order.

I cannot come up with a solution that

is tail-recursive,

does not use reverse,

only uses lists as data structure (using a functional data structure like a Haskell's sequence which allows to append elements is not an option),

has complexity linear in the size of the prefix, or at least does not have quadratic complexity (thanks to delnan for pointing this out).

Is there an alternative solution satisfying all the properties above? My intuition tells me that it is impossible to accumulate the prefix of a list in a tail-recursive fashion while maintaining the original order between the elements (i.e. without the need of using reverse to adjust the result) but I am not able to prove this.

Note

The solution using reverse satisfies conditions 1, 3, 4.

答:
Hmm, some cleverness continuations might work

First we write a function which takes a continuation, and returns a new continuation which cons a value onto the result

```<code>(define cons-later
  (lambda (c x)
    (lambda (r)
      (cons x (c r)))))
</code>```

Now take-while

```<code>(define take-while
  (lambda (pred xs)
    (define worker
      (lambda (c xs)
        (if (pred (car xs))
            (worker (cons-later c (car xs)) ; Make our new continuation
                    (cdr xs))
            (c '())))) ; Call the continuation

    (worker (lambda (x) x) xs)))
</code>```

We still pay the piper at some point though; this version takes up a bit more room than with reverse.

This uses functions of course, but since your reverse implementation did and was still counted as satisfying 1 3 and 4 I'll just innocently whistle.

Body:
Hmm, some cleverness continuations might work

First we write a function which takes a continuation, and returns a new continuation which cons a value onto the result

(define cons-later
  (lambda (c x)
    (lambda (r)
      (cons x (c r)))))

Now take-while

(define take-while
  (lambda (pred xs)
    (define worker
      (lambda (c xs)
        (if (pred (car xs))
            (worker (cons-later c (car xs)) ; Make our new continuation
                    (cdr xs))
            (c '())))) ; Call the continuation

    (worker (lambda (x) x) xs)))

We still pay the piper at some point though; this version takes up a bit more room than with reverse.

This uses functions of course, but since your reverse implementation did and was still counted as satisfying 1 3 and 4 I'll just innocently whistle.


答:
You asked:

But are there any more advantages to objects over static classes?

Before this question, you listed Polymorphism and being passed around as two benefits of using Objects. I want to say that those are the features of the OO paradigm. Encapsulation is another feature of the OO paradigm.

However, those are not the benefits. The benefits are:

Better abstractions

Better maintainability

Better testability

You said:

But recently when I stopped and thought about it, I realized that a static class would do just the same as an object, in a lot of the places where I normally use an object.

I think you have a valid point there. At its core, programming is nothing but transformation of data and creation of side effects based on data. Sometimes transforming data requires auxiliary data. Other times, it does not.

When you are dealing with the first category of transformations, the auxiliary data has to be either passed in as input or stored somewhere. An Object is the better approach that static classes for such transformations. An Object can store the auxiliary data and use it at the right time.

For the second category of transformations, a static class is as good as an Object, if not better. Mathematical functions are classic examples of this category. Most of standard C library functions fall into this category too.

You asked:

With an object, the calling line of code will look like this: Thing thing = fileLoader.load(file);

With a static class, it would look like this: Thing thing = FileLoader.load(file);

What's the difference?

If FileLoader does not, ever, need to store any data, I would go with the second approach. If there is a smidgen of a chance that it will need auxiliary data to perform the operation, the first approach is a safer bet.

You asked:

Are there any more advantages to objects other from the two that I listed? Please explain.

I listed the benefits (advantages) of using the OO paradigm. I hope they are self explanatory. If not, I'll be glad to elaborate.

You asked:

But what about 'static' parts of the system - that aren't going to be passed around? For example - a 'save file' mechanism. Why should I implement it in an object, and not a static class?

This is an example where a static class simply won't do. There are many ways to save your application data to a file:

Save it in a CSV file.

Save it in an XML file.

Save it in a json file.

Save it as a binary file, with direct dump of the data.

Save it directly to some table in a database.

The only way to provide such options is to create an Interface and create Objects that implement the interface.

In Conclusion

Use the right approach for the problem at hand. It is better not to be religious about one approach vs the other.


问:
Program coded in .Net
What does it generally mean when a programmer says his program/application was "coded in .Net"? </p>

<p>When I think of .Net I think of C# and Visual Basic. I don't usually think of any other language on this list: http://en.wikipedia.org/wiki/List_of_CLI_languages </p>

答:
It means that the program/application runs on the .NET Framework.

The .NET Framework includes a large library and provides language interoperability across several programming languages. Programs written for .NET Framework execute in the Common Language Runtime (CLR), an application virtual machine that provides services such as security, memory management, and exception handling.

C# and VB.NET are certainly two of the more common languages used on the .NET Framework, but they're not required.  There are several other first-class languages that would all be good choices, including F#, Boo, Nemerle, and even a .NET port of Clojure (a LISP variant).

F# is a functional/object-oriented language derived from the ML family of languages, especially OCaml.

Boo is a Python-like language with an emphasis on compiler pipeline extensibility that makes it an ideal platform for experimenting with domain-specific languages.

Nemerle is the "kitchen sink" of .NET languages, supporting several different programming paradigms.  JetBrains plans on making Nemerle a first-class citizen.

And of course, there are the "Iron" languages: IronRuby, IronPython and IronScheme.

All of these languages benefit from access to the broad spectrum of capabilities present in the .NET Framework class libraries.

Title: Program coded in .Net


问:
Is ASP.NET MVC too much overhead for smaller projects?
I will be honest I don't really know much about MVC other than the stuff you can read online in 5 minutes.  Unfortunately this doesn't really tell me whether its suited to smaller projects or not.

I also read this related question and its chosen answer, but the business perspective is not a concern in this case for me as I am the only one making it. The next answer proceeds to say why it is more flexible. Sure, that's great. But my question is again, if its an ideal choice for a small project.

For example I would rather use winforms to make a simple mockup of a small desktop program than do it on WPF because of the overhead of custom styling.

So I have a project that will essentially  have about 6-8 pages that read excel files and user input use that to pull a bit of data from databases and output  resulting excel files.

I will be the only one working on this project.  If I used webforms I would expect it to take no more than 2-3 weeks.

Now I am 100% comfortable with webforms. And I know its easy to do a small project in webforms.

But I have only heard good things about MVC so I am seriously considering it.

答:
I have found that it's not any more overhead than webforms.

The first time you use MVC it'll definitely be slower because you haven't used it before, but once you get the hang of it there's not really any difference in development speed.

My advice, go for it, get stuck in, you'll dig it after a while.


答:
MVC is a proven design pattern for web applications.The asp.net mvc provide loose coupling between the components thats why it is preffered in large enterprise level application, the web forms are preffered for small projects because wbe forms provide fast development I personally used mvc for many projects and I love it. I've seen the light and I will never go back to WebForms or ever suggest someone to work in WebForms no matter application is small or big.

Its obvious the asp.net mvc is more flexible than asp.net webforms in general.

Title: Is ASP.NET MVC too much overhead for smaller projects?

Body:
I will be honest I don't really know much about MVC other than the stuff you can read online in 5 minutes.  Unfortunately this doesn't really tell me whether its suited to smaller projects or not.

I also read this related question and its chosen answer, but the business perspective is not a concern in this case for me as I am the only one making it. The next answer proceeds to say why it is more flexible. Sure, that's great. But my question is again, if its an ideal choice for a small project.

For example I would rather use winforms to make a simple mockup of a small desktop program than do it on WPF because of the overhead of custom styling.

So I have a project that will essentially  have about 6-8 pages that read excel files and user input use that to pull a bit of data from databases and output  resulting excel files.

I will be the only one working on this project.  If I used webforms I would expect it to take no more than 2-3 weeks.

Now I am 100% comfortable with webforms. And I know its easy to do a small project in webforms.

But I have only heard good things about MVC so I am seriously considering it.


答:
I would not use Winforms vs WPF as an analogy to WebForms vs MVC. The former two are VERY different from one another (if you take WPF to the MVVM extreme anyway).

MVC is actually simpler than WebForms in many respects. If anything it is lighter weight and promotes faster development through a much simpler model of development. You also have the advantage of being able to use the much nicer Razor syntax which I don't believe you can use with WebFroms. MVC has very nice HTML Helpers to spit out the common HTML stuff and it has very nice, simple data binding.

There is also no hacky Viewstate. I personally don't miss not having event handling in my code behind, I will take an Action method on a controller any day.

Also, your application may end up growing or changing requirements. MVC will help you there. It will also give you a more marketable skillset because the industry is moving in the MVC direction.

I would never opt to use WebForms if I had the choice (which I currently don't) regardless of the size of the project.


问:
Architecture driven by users, or by actions/content?
I have a question about designing MVC app architecture.

Let's say our application has three main categories of views (items of type 1, items of type 2...). And we have three (or more in future) types of users - Admins, let's say Moderators and typical Users. And in the future there might be more of them. Admins have full access to app, Moderators can visit only 2/3 type of items, and Users can visit only basic type of items.

Should I divide my controllers/views/whatever like this:

Items "A", Items "B", Items "C", then make them 100% finished and at the end add access privileges?

Pros:

DRY option

Cons

Conditional expressions in views

Or another options: Items "A" / Admin, Items "A" / Moderator / Items "B" Admin ...?

Pros:

Divided parts of application for specific user (is that pros?)

Cons:

A lot of repeated code

I don't have great experience in planning such things so it would nice if you can give me some tips or links to learn something about it.

答:
MVP tells :

The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.

User privilege level is just a parameter - as any other parameter. That means that your models should dictate what is allowed depending on that parameter. There are no needs to do additional complication (divide application as you suggested).


问:
How many copies are needed to enlarge an array?
I am reading an analysis on dynamic arrays (from the Skiena's algorithm manual).

I.e. when we have an array structure and each time we are out of space we allocate a new array of double the size of the original.

It describes the waste that occurs when the array has to be resized.

It says that (n/2)+1 through n will be moved at most once or not at all. This is clear.

Then by describing that half the elements move once, a quarter of the elements twice, and so on, the
total number of movements M is given by:

This seems to me that it adds more copies than actually happen.

E.g.

if we have the following:

```<code>array of 1 element
+--+
|a |
+--+

double the array (2 elements)
+--++--+
|a ||b |
+--++--+

double the array (4 elements)
+--++--++--++--+
|a ||b ||c ||c |
+--++--++--++--+

double the array (8 elements)
+--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x |
+--++--++--++--++--++--++--++--+

double the array (16 elements)
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x ||  ||  ||  ||  ||  ||  ||  ||  |
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
</code>```

We have the x element copied 4 times, c element copied 4 times, b element copied 4 times and a element copied 5 times so total is 4+4+4+5 = 17 copies/movements.

But according to formula we should have 1*(16/2)+2*(16/4)+3*(16/8)+4*(16/16)= 8+8+6+4=26 copies of elements for the enlargement of the array to 16 elements.

Is this some mistake or the aim of the formula is to provide a rough upper limit approximation? Or am I missunderstanding something here?

答:
I believe the formula given in the book is simply incorrect.
The i multiplier has to be dropped from the formula to fix it.

Let's take the asker's example and call the array of 1 element array-1, the array of 2 elements -- array-2, the array of 4 elements -- array-4, and so on.

So, accordingly to the book, for this particular example the number of copyings is governed by the following formula:

```<code>
M = 1⋅8 + 2⋅4 + 3⋅2 + 4⋅1
</code>```

The first term of the sum 1⋅8 is for copying array-8's items into array-16.

We copy the array-4's items (a, b, c, c) twice. Once from the array-4 to array-8. And then when copying array-8's items to array-16 we copy (a, b, c, c) items for the second time. Accordingly to the book, hence the second term: 2⋅4.

But now notice that the 1⋅8 term already takes into account copying of (a, b, c, c) items from array-8 to array-16. Consequently the 2⋅4 term must not include the 2 multiplier.

The same logic applies to all the other terms. And so multiplying by i is a mistake.

Body:
I believe the formula given in the book is simply incorrect.
The i multiplier has to be dropped from the formula to fix it.

Let's take the asker's example and call the array of 1 element array-1, the array of 2 elements -- array-2, the array of 4 elements -- array-4, and so on.

So, accordingly to the book, for this particular example the number of copyings is governed by the following formula:

M = 1⋅8 + 2⋅4 + 3⋅2 + 4⋅1

The first term of the sum 1⋅8 is for copying array-8's items into array-16.

We copy the array-4's items (a, b, c, c) twice. Once from the array-4 to array-8. And then when copying array-8's items to array-16 we copy (a, b, c, c) items for the second time. Accordingly to the book, hence the second term: 2⋅4.

But now notice that the 1⋅8 term already takes into account copying of (a, b, c, c) items from array-8 to array-16. Consequently the 2⋅4 term must not include the 2 multiplier.

The same logic applies to all the other terms. And so multiplying by i is a mistake.


问:
Design for an interface implementation that provides additional functionality
There is a design problem that I came upon while implementing an interface:

Let's say there is a Device interface that promises to provide functionalities PerformA() and GetB(). This interface will be implemented for multiple models of a device. What happens if one model has an additional functionality CheckC() which doesn't have equivalents in other implementations?

I came up with different solutions, none of which seems to comply with interface design guidelines:

To add CheckC() method to the interface and leave one of its
implementations empty:

```<code>interface ISomeDevice
{
    void PerformA();
    int GetB();
    bool CheckC();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        return true; // without checking anything
    }
}
</code>```

This solution seems incorrect as a class implements an interface without truly implementing all the demanded methods.

To leave out CheckC() method from the interface and to use explicit cast in order to call it:

```<code>interface ISomeDevice
{
    void PerformA();
    int GetB();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
}

class DeviceManager
{
    private ISomeDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            DeviceModel1 newDevice = myDevice as DeviceModel1;
            bool c = newDevice.CheckC();
        }
    }
}
</code>```

This solution seems to make the interface inconsistent.

For the device that supports CheckC(): to add the logic of CheckC() into the logic of another method that is present in the interface. This solution is not always possible.

So, what is the correct design to be used in such cases? Maybe creating an interface should be abandoned altogether in favor of another design?

答:
It depends a lot, really (now that's a surprise).
Here are a few things to consider:

What is the contract of the interface?

If the interface should allow performA and getB, but device2 requires checkC to be called, then it does not adhere to the interface. If the interface defines that C must be checkable, then device1 does not adhere. If your algorithm uses that check, it might be the latter.

Can you define a reasonable default behavior?

If it's just a check you could always return true.

Is it an optional operation?

Define it to be optional. The interface might specify that throwing an exception is allowed. Add another method CanCheckC that returns whether the operation is supported. Or add TryCheckC that returns true iff a check was performed and returns the result in an out-parameter.

Is it a new type of interface?

If, in general, devices can't check C but some class of device can, maybe this is a new interface. So add a new interface IDeviceWithCCheck that provides the additional operations and use type checks in your algorithm before you cast.


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答:
I think the ideal is that names should be descriptive unless...

The idea that names can (maybe should) be shorter - and thus by implication less descriptive - if they have limited scope is only one reason to deviate from the ideal.

Personally I frequently use short names for a small number of repeatedly-referenced entities. Frequently-called app-specific subroutines, for example.

Title: Are short identifiers bad?

ContentLicense: CC BY-SA 2.5


问:
How can Swift be so much faster than Objective-C in these comparisons?
Apple launched its new programming language Swift at WWDC14. In the presentation, they made some performance comparisons between Objective-C and Python. The following is a picture of one of their slides, of a comparison of those three languages performing some complex object sort:

There was an even more incredible graph about a performance comparison using the RC4 encryption algorithm.

Obviously this is a marketing talk, and they didn't go into detail on how this was implemented in each. I leaves me wondering though:

How can a new programming language be so much faster?

Are the Objective-C results caused by a bad compiler or is there something less efficient in Objective-C than Swift?

How would you explain a 40% performance increase? I understand that garbage collection/automated reference control might produce some additional overhead, but this much?

答:
First, (IMO) comparing with Python is nearly meaningless. Only comparison with Objective-C is meaningful.

How can a new programming language be so much faster?

Objective-C is a slow language. (Only C part is fast, but that's because it's C) It has never been extremely fast. It was just fast enough for their (Apple's) purpose, and faster then their older versions. And it was slow because...

Do the Objective-C results from a bad compiler or is there something less efficient in Objective-C than Swift?

Objective-C guaranteed every method to be dynamically dispatched. No static dispatch at all. That made it impossible to optimize an Objective-C program further. Well, maybe JIT technology can be some help, but AFAIK, Apple really hate unpredictable performance characteristics and object lifetime. I don't think they had adopted any JIT stuff. Swift doesn't have such dynamic dispatch guarantee unless you put some special attribute for Objective-C compatibility.

How would you explain a 40% performance increase? I understand that garbage collection/automated reference control might produce some additional overhead, but this much?

GC or RC doesn't matter here. Swift is also employing RC primarily. No GC is there, and also will not unless there's some huge architectural leap on GC technology. (IMO, it's forever) I believe Swift has a lot more room for static optimization.  Especially low level encryption algorithms, as they usually rely on huge numeric calculations, and this is a huge win for statically dispatch languages.

Actually I was surprised because 40% seems too small. I expected far more. Anyway, this is the initial release, and I think optimization was not the primary concern. Swift is not even feature-complete! They will make it better.

Update

Some keep bugging me to argue that the GC technology is superior. Though stuff below can be arguable, and just my very biased opinion, but I think I have to say to avoid this unnecessary argument.

I know what conservative/tracing/generational/incremental/parallel/realtime GCs are and how they are different. I think most of readers also already know that. I also agree that GC is very nice in some field, and also shows high throughput in some cases.

Anyway, I suspect the claim of GC throughput is always better than RC. Most of overhead of RC comes from ref-counting operation and locking to protect ref-count number variable. And RC implementation usually provide a way to avoid counting operations. In Objective-C, there's __unsafe_unretained and in Swift, (though it's still somewhat unclear to me) unowned stuffs. If the ref-counting operation cost is not acceptable, you can try to opt-out them selectively by using the mechanics. Theoretically, we can simulate almost unique-ownership scenario by using non-retaining references very aggressively to avoid RC overhead. Also I expect the compiler can eliminate some obvious unnecessary RC operations automatically.

Unlike RC system, AFAIK, partial opt-out of reference-types is not an option on GC system.

I know there're many released graphics and games which are using GC based system, and also know most of them are suffering by lack of determinism. Not only for performance characteristic, but also object lifetime management. Unity is mostly written in C++, but the tiny C# part causes all the weird performance issues. HTML hybrid apps and still suffering by unpredictable spikes on any system. Used widely doesn't mean that's superior. It just means that's easy and popular to people who don't have many options.

Update 2

Again to avoid unnecessary argument or discussion, I add some more details.

@Asik provided an interesting opinion about GC spikes. That's we can regard value-type-everywhere approach as a way to opt-out GC stuff. This is pretty attractive, and even doable on some systems (purely functional approach for example). I agree that this is nice in theory. But in practice it has several issues. The biggest problem is partial application of this trick does not provide true spike-free characteristics.

Because latency issue is always all or nothing problem. If you have one frame spike for 10 seconds (= 600frames), then the whole system is obviously failing. This is not about how better or worse. It's just pass or fail. (or less then 0.0001%) Then where is the source of GC spike? That's bad distribution of GC load. And that's because the GC is fundamentally indeterministic. If you make any garbage, then it will activate the GC, and spike will happen eventually. Of course, in the ideal world where GC load will be always ideal, this won't happen, but I am living in real world rather than imaginary ideal world.

Then if you want to avoid spike, you have to remove all the ref-types from the whole system. But it's hard, insane, and even impossible due to unremovable part such as .NET core system and library. Just using non-GC system is far easier.

Unlike GC, RC is fundamentally deterministic, and you don't have to use this insane optimization (purely-value-type-only) just only to avoid spike. What you have to do is tracking down and optimizing the part which causes the spike. In RC systems, spike is local algorithm issue, but in GC systems, spikes are always global system issue.

I think my answer is gone too much off-topic, and mostly just repetition of existing discussions. If you really want to claim some superiority/inferiority/alternative or anything else of GC/RC stuffs, there're plenty of existing discussions in this site and StackOverflow, and you can continue to fight at there.


问:
Website File and Folder Structure
I am having a problem learning how proper website structure should be. And by that I mean how to code the pages and how folder structure should be.

Currently I am navigating around my website using GET variables in PHP when you want go to another page, so I am always loading the index.php file. And I would load the page I wanted like so:

```<code>$page = "error";

if(isset($_GET["page"]) AND file_exists("pages/".$_GET["page"].".php")) {

    $page = $_GET["page"];

} elseif(!isset($_GET["page"])) {

    $page = "home";

}
</code>```

And this:

```<code><div id="page">
    <?php
         include("pages/".$page.".php");
    ?>
</div>
</code>```

The reason I am doing this is because it makes making new pages a lot easier as I don't have to link style sheets and javascript in every file like so:

```<code><head>
    <title>
        Website Name
    </title>

    <link href='http://fonts.googleapis.com/css?family=Lato:300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/style.css" type="text/css">
    <link rel="shortcut icon" href="favicon.png"/>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>

</head>
</code>```

There is a lot of problems doing it this way as URLs don't look normal ("?page=apanel/app") if I am trying to access a page from inside a folder inside the pages folder to prevent clutter.

Obviously this is not the only way to go about it and I can't find the proper way to do it because I'm sure websites don't link style sheets in every file as that would be very bad if you changed a file name or needed to add another file you would have to change it in every file.

If anyone could tell me how it is actually done or point me towards a tutorial that would be great.

Thanks for your time :)

答:
You may not realise it, but you're actually using the Front Controller design pattern. It's very common to use a single index.php as the starting point for every page. All of the big PHP MVC frameworks (such as Zend, Symfony, Laravel) do this.

In order to make the URLs look nice, you usually need to add something into your Apache configuration (assuming that Apache is your web server). With Apache, this is typically done by adding a RewriteRule to a file .htaccess that translates a path such as /mypage into a path such as /index.php?page=mypage.

The Laravel installation guide here http://laravel.com/docs/installation#pretty-urls gives a typical example of what should be in the .htaccess.

A word of warning, the code you pasted in your question has some dangerous security flaws. An attacker could easily make your page include files you didn't intend by passing in URLs such as /index.php?page=../../../../etc/passwd or something like that. You should sanitise the input (perhaps by removing all '/' characters) before using it in the 'include' line.

Title: Website File and Folder Structure


答:
Consider this solution:

```<code>interface IDevice
{
    void PerformA();
    int GetB();
}

interface INewDevice : IDevice
{
    bool CheckC();
}

class DeviceModel1 : INewDevice
{
    ...
}

class DeviceModel2 : IDevice
{
    ...
}

class DeviceManager
{
    private IDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            INewDevice newDevice = myDevice as INewDevice;
            bool c = newDevice.CheckC();
        }
    }
}
</code>```

Wherever you don't care about the difference between an IDevice and an INewDevice, you can use the methods common to both. If you do need behavior specific to new devices, you cast to the new interface, so you don't tie yourself down to any particular implementation.

If the casting bothers you, see this question for ways of creating a new type that may contain a value of type A or B (or C, or ...) and provides a type-safe way of taking actions depending on what the type of the value actually is. I especially like Joey's answer for its use of named parameters and lambdas. You could for example make collections that hold Either<IDevice, INewDevice> and then you can use the Match method to avoid any casting. E.g.

```<code>IList<Either<IDevice, INewDevice>> devices = // get a list of devices
foreach (var device in devices) {
    device.Match(
        Left: oldDevice => // things to do if it's an old device
        Right: newDevice => // things to do if it's a new device
    );
}
</code>```

There's no risk of doing a wrong cast using this approach.

Title: Design for an interface implementation that provides additional functionality

Body:
There is a design problem that I came upon while implementing an interface:

Let's say there is a Device interface that promises to provide functionalities PerformA() and GetB(). This interface will be implemented for multiple models of a device. What happens if one model has an additional functionality CheckC() which doesn't have equivalents in other implementations?

I came up with different solutions, none of which seems to comply with interface design guidelines:

To add CheckC() method to the interface and leave one of its
implementations empty:

```<code>interface ISomeDevice
{
    void PerformA();
    int GetB();
    bool CheckC();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        return true; // without checking anything
    }
}
</code>```

This solution seems incorrect as a class implements an interface without truly implementing all the demanded methods.

To leave out CheckC() method from the interface and to use explicit cast in order to call it:

```<code>interface ISomeDevice
{
    void PerformA();
    int GetB();
}

class DeviceModel1 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
    public bool CheckC() {
        bool res;
        // assign res a value based on some validation
        return res;
    }
}

class DeviceModel2 : ISomeDevice
{
    public void PerformA() { // do stuff }
    public int GetB() { return 1; }
}

class DeviceManager
{
    private ISomeDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            DeviceModel1 newDevice = myDevice as DeviceModel1;
            bool c = newDevice.CheckC();
        }
    }
}
</code>```

This solution seems to make the interface inconsistent.

For the device that supports CheckC(): to add the logic of CheckC() into the logic of another method that is present in the interface. This solution is not always possible.

So, what is the correct design to be used in such cases? Maybe creating an interface should be abandoned altogether in favor of another design?

Body:
Consider this solution:

interface IDevice
{
    void PerformA();
    int GetB();
}

interface INewDevice : IDevice
{
    bool CheckC();
}

class DeviceModel1 : INewDevice
{
    ...
}

class DeviceModel2 : IDevice
{
    ...
}

class DeviceManager
{
    private IDevice myDevice;
    public void ManageDevice(bool newDeviceModel)
    {
        myDevice = (newDeviceModel) ? new DeviceModel1() : new DeviceModel2();
        myDevice.PerformA();
        int b = myDevice.GetB();
        if (newDeviceModel)
        {
            INewDevice newDevice = myDevice as INewDevice;
            bool c = newDevice.CheckC();
        }
    }
}

Wherever you don't care about the difference between an IDevice and an INewDevice, you can use the methods common to both. If you do need behavior specific to new devices, you cast to the new interface, so you don't tie yourself down to any particular implementation.

If the casting bothers you, see this question for ways of creating a new type that may contain a value of type A or B (or C, or ...) and provides a type-safe way of taking actions depending on what the type of the value actually is. I especially like Joey's answer for its use of named parameters and lambdas. You could for example make collections that hold Either<IDevice, INewDevice> and then you can use the Match method to avoid any casting. E.g.

IList<Either<IDevice, INewDevice>> devices = // get a list of devices
foreach (var device in devices) {
    device.Match(
        Left: oldDevice => // things to do if it's an old device
        Right: newDevice => // things to do if it's a new device
    );
}

There's no risk of doing a wrong cast using this approach.


问:
How does dependecy injection increase coupling?
On the Wikipedia page on dependency injection, the disadvantages section tells us this:

Dependency injection increases coupling by requiring the user of a subsystem to provide for the needs of that subsystem.

with a link to an article against dependency injection.

Dependency injection makes a class use the interface instead of the concrete implementation. That should result in decreased coupling, no?

What am I missing? How is dependency injection increasing coupling between classes?

答:
Suppose you have a subsystem S that depends on a database connection D. Without dependency injection, there is a relatively tight coupling between S and D, because S needs to know both how to use D and how to create it. The rest of the system, however, can be blissfully unaware of this dependency between S and D.

With dependency injection, the coupling between S and D becomes looser, because you remove from S the knowledge how to create a D. S just needs to know how to use it. The increased overall coupling comes from the fact that other parts of the system now need to know about D and possibly how to create one. The extent of this increase in coupling depends on how the dependency on D gets injected into S:

With constructor injection the creator of S needs a dependency on D and possibly the knowledge how to create one.

With method-level injection, each caller of a method of S through which a D gets injected needs a dependency on D and possibly the knowledge how to create one.

In either case, the number of classes that depends on D increases and the knowledge how to create a D still needs to be present somewhere in the system. This creates an overall increase of coupling.


答:
So, what am I missing?

Dependency Injection decreases coupling between a class and its dependency. But it increases the coupling between a class and its consumer (since the consumer needs more info to create it) and the dependency and its consumer (since the consumer needs to know the dependency to use).

Very often, this is a good trade off. The class shouldn't know the details about its dependencies beyond an interface, and it should be the responsibility of the application to tie specific bits of code together.

Title: How does dependecy injection increase coupling?

Body:
On the Wikipedia page on dependency injection, the disadvantages section tells us this:

Dependency injection increases coupling by requiring the user of a subsystem to provide for the needs of that subsystem.

with a link to an article against dependency injection.

Dependency injection makes a class use the interface instead of the concrete implementation. That should result in decreased coupling, no?

What am I missing? How is dependency injection increasing coupling between classes?


问:
Pros and Cons of Facebook's React vs. Web Components (Polymer)
What are the main benefits of Facebook's React over the upcoming Web Components spec and vice versa (or perhaps a more apples-to-apples comparison would be to Google's Polymer library)?

According to this JSConf EU talk and the React homepage, the main benefits of React are:

Decoupling and increased cohesion using a component model

Abstraction, Composition and Expressivity

Virtual DOM & Synthetic events (which basically means they completely re-implemented the DOM and its event system)

Enables modern HTML5 event stuff on IE 8

Server-side rendering

Testability

Bindings to SVG, VML, and <canvas>

Almost everything mentioned is being integrated into browsers natively through Web Components except this virtual DOM concept (obviously). I can see how the virtual DOM and synthetic events can be beneficial today to support old browsers, but isn't throwing away a huge chunk of native browser code kind of like shooting yourself in the foot in the long term? As far as modern browsers are concerned, isn't that a lot of unnecessary overhead/reinventing of the wheel?

Here are some things I think React is missing that Web Components will take care of for you. Correct me if I'm wrong.

Native browser support (read "guaranteed to be faster")

Write script in a scripting language, write styles in a styling language, write markup in a markup language.

Style encapsulation using Shadow DOM

React instead has this, which requires writing CSS in JavaScript. Not pretty.

Two-way binding

答:
Another answer in one point specifically :

Write JavaScript in vanilla JavaScript, write CSS in CSS, write HTML
  in HTML.

Nothing prevents you from writing Javascript in, say, CoffeeScript, TypeScript, ClojureScript or anything else. It's purely a matter of preference.

HTML is the best DSL for static HTML documents. But it provides nothing for dynamic HTML. And in the browser, the best language to make HTML dynamic is Javascript, not pure HTML with ad-hoc Javascript DOM manipulation or template language like Handlebars that are not even half languages.

For CSS, if your CSS is static, you write it as usual. If it needs to be dynamic based on some runtime values, it's the same story as HTML : Javascript is the best way to make it dynamic.


问:
Is the test, which touches the filenames under directory, a kind of unittest?
I was told that unittest is fast and the tests which touches DB, across network, and touches FileSystem are not unittest.

In one of my testcases, its input are the file names (amount about 300~400) under a specific folder. Although these input are part of file system, the execution time of this test is very fast.

Should I moved this test, which is fast but touches file system, to higher level test?

答:
Speed shouldn't be the only determination when figuring out what type of test you are writing / running.  A SQL query could take 10 milliseconds, which could be considered fast.  Reading from a file on a system could take 5 milliseconds, which too could also be considered fast.

Here are some of common criteria for determining if something is a unit test (this list is not all inclusive):

Has no external dependencies (sql server, file server, network, ...)

Repeatable results, if the code doesn't change then the test results shouldn't change

Fully isolated, one test should not depend on another test to run

Finally, be fast

Your test touches the file system, which fails two of the above four criteria.  If the folder is renamed, a file is removed, or the network connection fails, then your test could fail.  This means it is a integration test, or from what you wrote in the "fulltest" project.  Integration tests are still important and are useful.  If you want to make your test a true unit test then I would follow the links @gnat provided.


问:
Best Practice: What can be the hashCode() method implementation if custom field used in equals() method are null?
What is the best practice to return a value for hashCode() method if custom field used in equals are null ?

I have a situation, where equals() override is implemented using custom fields. Usually it is recommented to override hashCode() using that custom fields used in equals(). But if all the custom fields used in equals() are null, then what would be the best implementation for hashCode()?

Example:

```<code>class Person {
    private String firstName;
    private String lastName;
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    @Override
    public boolean equals(Object object) {
        boolean result = false;
        if (object == null || object.getClass() != getClass()) {
            result = false;
        } else {
            Person person = (Person) object;
            if (this.firstName == person.getFirstName()
                && this.lastName == tiger.getLastName()) {
                result = true;
            }
        }
        return result;
    }
    @Override
    public int hashCode() {
        int hash = 3;
        if(this.firstName == null || this.lastName == null) {
            // <b>What is the best practice here, </b>
            // <b>is return super.hashCode() better ?</b>
        }
        hash = 7 * hash + this.firstName.hashCode();
        hash = 7 * hash + this.lastName.hashCode();
        return hash;
    }
}
</code>```

is it required to check for null in hashCode() ?

If yes, what should be returned if custom values are null ?

答:
I would do hashCode() as follows

public int hashCode() {
  String str = this.firstName + " " + this.lastName;
  return str.hashCode();
}

That would satisfy the requirements for hashCode()
equal objects have same hashCode()

Doesn't have any null problem at all.