答:
I would start by creating a class of general-purpose serializable objects that are capable of standing in for any object that needs to be serialized. Each object would contain a representation of every field that needs to be serialized, and the type and version of the object. You may want to use JSON or something similar for this part.

Each serializable class would need a constructor that takes a general-purpose object and throws an exception if the type, version, or fields don't match what the class needs. For the other direction each class would need a method that converts an object of that class into a general-purpose object. If you want your serialization to include multiple references to a single object then you can pass around an additional object to take care of mapping between POJOs and general-purpose objects.

Finally each serializable class needs a static method for converting from old versions to the current version. For the first version this would do nothing, but every time you modify the class you would increment the current version and add a conversion step that converts a general-purpose object for the previous version into a general-purpose object for the new version. You could have a switch statement with no breaks that switches on the version of the given object. The first case would convert an object of the first version into an object of the second version, followed by a case for converting the second version into the third version, and then you can fall all the way through until you have an object of the current version at the bottom. Each new version just requires adding a single case to the bottom of the switch statement that represents the changes that have been made.

Title: Storing object-graphs with class-evolution in Java with transformation (long time archiving)

Body:
Abstract

A common problem is to store objects (with graph), and to load them back. This is easy as long the stored object representation matches the executing code. But as time goes by, requirements change and stored objects do not match any longer the code. The stored objects should not loose their data, and the code in the clients should work with the latest object-models.

So a transformation has to occur somehow between loading the data and returning a object to the client.

I know that there exist some libraries such as XStream, gson, protobuf and avro. They could load older objects, but afaik just ignore data that does not match any longer the fields in the class (maybe I missed something).

(When I'm talking about storing and serialization I do not mean Java's built in serialization mechanism.)

Question

So what is the question? I'm now researching for some time, and there seems no library that adresses this issue (class evolution) without data-loss. I hope to find another working solution or idea how to implement it by myself here.

I have some requirements:

File-based - I want to be able to store the serialized object on disk

Appendable - I want to append multiple objects to one file without loading the whole file in memory again and again

Support for multiple versions in one file - A file could contain objects with different version (only of the same type)

Transformation - Data should be accessible by using the same type, even when changed in between.

Generic - The mechanism itself has to be generic, so I could use it for different objects (different objects do not get mixed in one file, only different versions of one type).

It would be nice if the storing format is human-readable.

Already stored objects are not updateable (at least not without huge effort). Think of an long-term archive.

Example

I could give an example for better illustration. Let's suppose we have two Pojos that we want to serialize.

```<code>public class MyPojo {
    String text;
    Long number;
    Integer[] values;
    SubPojo pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

In the next version we might have renamed a field (text->content), changed a type (Integer[]->List), and have transformed a field to List (SubPojo->List) where the previous field now is the first element of the new list (not loosing data, just transforming to new representation).

```<code>public class MyPojo {
    String content;
    Long number;
    List<Integer> values;
    List<SubPojo> pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

Some pseudocode how the client might take use of this:

```<code>// Write
Serializer ser = new Serializer();
MyPojo pojo = new MyPojo();
pojo.xxx = ...; // set fields
ser.store(pojo, file, append);

// Read (a version later)
Serializer ser = new Serializer();
ser.registerTransformer(new TransformerV1ToV2());
List<MyPojo> pojos = ser.load(file);
</code>```

This approach has some drawbacks:

The transformer have to work on some kind of intermediate format (could be the backed stored format such as json or xml)

You don't know how the class format was at some point in time, since you're only transforming relative to the previous version and mapping to the final class, making search for errors hard

Performance (depending on how the transformation happens)


问:
Object inheritance and method parameters/return types - Please check my logic
I'm preparing for a test and doing practice questions, this one in particular I am unsure I did correctly:

We are given a very simple UML diagram to demonstrate inheritance: I hope this is clear, it shows that W inherits from V and so on:

```<code>                  |-----Y
V <|----- W<|-----|
                  |-----X<|----Z
</code>```

and this code:

```<code>public X method1(){....}
method2(new Y());
method2(method1());
method2(method3());
</code>```

The questions and my answers:

Q: What types of objects could method1 actually return?

A: X and Z, since the method definition includes X as the return type and since Z is a kind of X is would be OK to return either.

Q: What could the parameter type of method2 be?

A: Since method2 in the code accepts Y, X and Z (as the return from method1), the parameter type must be either V or W, as Y,X and Z inherit from both of these.

Q: What could return type of method3 be?

A: Return type of method3 must be V or W as this would be consistent with answer 2.

答: method3 might have a return type that is anything that could be accepted by method2, which means V, W and every subclass of W since all of them could be accepted by method2. Given how little we know about method3 there is really no cause to pretend we know that it's return type must be just V or W. The less we know, the more possibilities there are.

ContentLicense: CC BY-SA 3.0


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
C# is perfectly fine to start programming in.

It is what I was told to start with, without even having the chance to dabble in anything else (apart from the Hello World in Java, some basic LOGO stuff, and some things in Scratch, but nothing "Serious").

Overall, it can be difficult - there are a lot of things that don't seem intuitive, and it does have it's limitations, but I think it encourages good coding and is great once you get the hang of it. I mean, it gives you more power and is a little more professional than Python (which is usually suggested), and that would make a world of difference - trying C++ after C# was not too painful, but if I had started with Python, then it would be a very big hurdle indeed, even just at the syntax level.

Also, it has good cross platform support in the form of Mono (for those of you who think Mono is not a big deal - the Unity Game Engine lets you code in a version of it). It also is pretty useful for most things, whether it be game scripting, or web designing, or Windows Applications. Of course, some languages will be better for certain lines, so it will depend on what general direction you are planning to go in - for example, if you are going in the web direction, then C# (ASP.NET) would definitely be a good idea. If you are planning to get into games, then you should think about C++ instead.

In the end, it is well worth learning it, even if you don't end up using it in favour of the simplicity of Python or the archaic nature of Java (as the release cycle for Java is REALLY slow) - you learn good coding practices, while not being too complicated for a newbie to learn.


问:
history and application areas of 'pull'/'push' programming paradigm
Recently reading a lot materials on Reactive Programming, one thing frequently mentioned is the 'PUSH' versus 'PULL' style of application.  Event driven ( Reactive programming )

Some of the authors say that both these styles have their area of applications, but aren't most application domains we are trying modeling are all changing rapidly in real world and thus  event driven is more appropriate?

And why we started from the 'PULL' approach and now turning into 'PUSH' approach, are there specific reasons causing the change?

答:
Even today, there are some areas, where you have to pull data, because a push option is simply not available to you. As far as those that I know of, these have been around for a long long time, such that early systems may have simply accepted from those that pull is the way to go.

Let's start with a very simply example: you want to monitor a folder on your harddrive and do something whenever a new file appears in that folder. In modern languages, you are offered abstractions that allow you to register a sort of listener, which will be called once a file is detected. Earlier, when these abstractions were not yet available, you had to check for yourself, by continuously pulling the folder information and check for a new file.

While this may sound old to you, the problem appears again in a modern setting, when you go from a simple folder to f.ex. a source code repository. Most of us have a CI server like Jenkins running, and lo and behold, how does it get to know that someone commited something to the project's SVN repository? It pulls data from the repo every x minutes (or whatever is configured for the pull interval). As usual, we could invest some effort to move this towards a push-style implementation, but you'd have to find something that works for all code repository implementations, which is not that simple after all.

Finally, in the embedded area, the pull approach has been predominant for a long time and will not go away anytime soon either. When you have simple hardware that you can access, you will often end up having to pull its data and check for changes. Only higher-level hardware elements, like a CPU, can provide abstractions over that. On the lowest level, however, you simply have 0 and 1, power off or on.

For this reason, I assume that early software development, which was still close to the hardware level, was influenced by having to pull data from hardware elements. I still know lots of embedded programmers, which still write endless polling loops that just keep getting the latest sensor data in order to do stuff whenever a significant enough change happened. So writing pull-based code just seems to come naturally from this perspective.

What we have done in the past, though, was to add an abstraction layer on top, which gave us the insight that a push approach is much better in many respects. Hence, we continously looked for ways to move from one to the other. People realized that if a folder watch can be implemented such that all watchers are simply notified via push-style approach, then our resulting software that we have to write gets much easier, hence, cheaper and faster to market.

To answer your question on appropriateness: if you already have a push-style interface available for use, then most likely it's the better alternative. But there are cases, where you don't have such an interface yet and are left with but two options: either create the abstraction level yourself, or go straight for the pull approach. Appropriateness in general depends on your actual context and some rare cases (see above) exist, in which your only feasible way is to pull.


问:
Should I start a project I am hoping to recruit others to?
I have an idea for a program that I think is a good one (Don't we all?).  I am an amateur programmer and would like to recruit some more advanced programmers onto the project since there are some aspects that I am not skilled enough to do myself.  Is it better to

a) Develop the software on my own as much as I can, even though it will be amateurish, and then show a demo to potential recruits

or

b) Try and recruit some more advanced programmers and seek their advice and guidance before I get started so that it is done correctly from the beginning?

I would especially love it if someone has any experience of being in a similar position, but sage speculation is welcome too.

答:
Do it yourself - a half baked, poorly coded, badly designed, dripping-from-all-sides, heavily bandaged version 0.1 for your software is far better than no software.

Also remember that you need to sell it to your customers, not your developers. If you find paying customers for software you can easily get developers to add to your team. And customers need to see SOMETHING. If you have some large customers lined up for v1 of your software whenever it is going to come out, I don't see why developers won't come onboard. Besides you are paying them aren't you?! ;)

And yeah this comes from experience. Customers can tell you much more about your product than other developers can. (not how to build, but what to build)

ContentLicense: CC BY-SA 2.5


问:
How do you avoid looping mistakes? Mistakes that are not detected by systems
I had this crazy initialisation --

documentList = new ArrayList<Map<String,Integer>>();

which I intended to store a new map everytime in a loop but unfortunately put itself inside the loop. And you know the havoc.

How do you detect such mistakes? I might be looking for suggestions on 'recommended debugging techniques' but am also looking for more expert advice

答:
These mistakes are detectable by the system and simple to avoid: embrace immutability.

At least declare your documentList as final. This immediately causes the compiler to inform you about this particular error. Unfortunately, Java does not have all the good things from functional programming, like real immutable lists and higher-order functions (yet), but at least final means you cannot replace your initial list with a completely new one. You can still make mistakes like calling documentList.clear(), but those are much less likely to happen by chance.

Hence, as usual, I try not to even go down the road of having to detect such mistakes, but I try to write code in a style that immediately ensures such a mistake cannot happen at all. For good reasons, mutability is spelled as t-r-o-u-b-l-e, so never walk that road unless you have to. The more parts of your code that can be declared final, the better.


问:
I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?

答:
The most important thing in writing software is making it readable. All other considerations are secondary, including making it efficient and making it correct. If it's readable, the rest can be taken care of in maintenance, and if it's not readable then you're better off just throwing it away. Therefore, you should throw exceptions when it enhances readability.

When you're writing some algorithm, just think about the person in the future who will be reading it. When you come to a place where there could be a potential problem, ask yourself if the reader wants to see how you handle that problem now, or would the reader prefer to just get on with the algorithm?

I like to think of a recipe for chocolate cake. When it tells you to add the eggs, it has a choice: it can either assume you have eggs and get on with the recipe, or it can begin an explanation for how you can get eggs if you don't have eggs. It could fill a whole book with techniques for hunting wild chickens, all to help you bake a cake. That's good, but most people aren't going to want to read that recipe. Most people would prefer to just assume that eggs are available, and get on with the recipe. That's a judgement call that authors need to make when writing recipes.

There can't be any guaranteed rules about what makes a good exception and what problems should be handled immediately, because it requires you to read the mind of your reader. The best you'll ever do is rules of thumb, and "exceptions are only for exceptional circumstances" is a pretty good one. Usually when a reader is reading your method they are looking for what the method will do 99% of the time, and they'd rather not have that cluttered with bizarre corner cases like dealing users entering illegal input and other stuff that almost never happens. They want to see the normal flow of your software laid out directly, one instruction after another as if problems never happen. Understanding your program is going to be hard enough without having to deal with constantly going off on tangents to deal with every little problem that might come up.


答:
The best way to catch such bugs is to prevent them from rearing their head during runtime.
You can achieve that in several ways (which are not mutually exclusive):

Write your code in a style that allows a compiler to pick up on the errors. Some examples are to make liberal use of immutability (const/final, as also described in the answer by @Frank), or to write equality test like this: 42 == x in a context where assignment would also be legal.

Have a second pair of eyes look over your code (as in, perform a code review).

Title: How do you avoid looping mistakes? Mistakes that are not detected by systems

Body:
I had this crazy initialisation --

documentList = new ArrayList<Map<String,Integer>>();

which I intended to store a new map everytime in a loop but unfortunately put itself inside the loop. And you know the havoc.

How do you detect such mistakes? I might be looking for suggestions on 'recommended debugging techniques' but am also looking for more expert advice


答: In general you should write unit tests for preventing mistakes. With test driven development you build your components in small increments and constantly strengthen your test harness. As a result you have a more-or-less bug-free component which you don't need to debug afterwards.</p>


问:
Language with syntactic sugar that translates to C++ that looks "hand-written"
I'm a college student and I have homework in C++.

My professor wants separate hpp and cpp files for each C++ class. And it just didn't feel good how much I had to type, and how much I had to click to create two new files for every class.

I haphazardly put together a simple Python script that would read a single file and generate all the needed classes (the easy stuff like class name, list of members, and list of things to #include I sprinkled with syntactic sugar, but the hard stuff to parse like typenames and function bodies I copied and pasted for the most part, except my script pokes around in a very primitive way to qualify method signatures with the class name when it generates the implementation file).

And I felt pretty good about it.

But I realized, that if a lot of other people had worked on a similar problem in the past, they probably could have done it better.

I know that Chicken scheme translates to C, and so does vala and genie, but from what I understand, with these sorts of translators, you don't really have full control over the C output.

Do you know of any translators that output C++ that largely keeps the semantics of C++ intact, so that the output C++ files look handwritten, but the source language is just loaded with wonderful syntax that makes life easier? Maybe even have the language mess with the body of functions so that if I typed something like vector<int> v = [1,2,3,4,5] it would become vector<int> v; v.push_back(1); v.push_back(2); .. in the generated source? Maybe have braces automatically inserted based on indentation? Have newlines serve as semicolons?

答:
No, a language like you are looking for is unlikely to exist.

I vaguely remember a few efforts to create new languages that tried to remove such warts out of C++ as header files, but invariably they are either compiled directly (no translation to C++) or the C++ they generate has a distinct machine-generated look and feel, because producing readable C++ wasn't (enough of) a requirement.

In most cases, the duplication that you get from having separate declarations and definitions is taken care of to a sufficient degree by advanced editor features, like macros, wizards and refactoring tools.


问:
Is it common to prototype in a higher level language?
I'm currently toying with the idea of embarking on a project that far exceeds my current programming ability in a language I have very little real world experience in (C). Would it be valuable to prototype in a higher level language that I'm more familiar with (like Perl/Python/Ruby/C#) just so I can get the overall design going?

Ultimately, the final product is performance sensitive (it's a database engine), hence the choice of C, but I'm afraid not knowing C well will make me lose the forest for the trees.

While searching for similar questions, I noticed one fellow mention that programmers used to prototype in Prolog, then crank it out in assembler.

答:
I think C's fame is well deserved, because the magnificent product Unix was written in C. However, compared to people who know C best, I am quite sceptical about why it should be used. It is said that Ken Thompson (after writing a first version of Unix in assembly language) began to write Unix in Fortran, but gave up after a week or a month, and began to use C which was being developed by his colleague Ken Ritchie at the same time.

I was astounded to read recently that Fortran is faster than C and C++.

Richard Mullins


问:
The Inglish parser (for The Hobbit 1982)
Was fascinated to read about the text adventure game The Hobbit which featured an incredibly robust parser called "Inglish":

...Inglish allowed one to type advanced sentences such as "ask Gandalf about the curious map then take sword and kill troll with it". The parser was complex and intuitive, introducing pronouns, adverbs ("viciously attack the goblin"), punctuation and prepositions and allowing the player to interact with the game world in ways not previously possible.

I'm wondering if anyone knows about the history and/or legacy of the Inglish parser engine and the programmer(s) who developed it.

答:
From The Digital Antiquarian's article on "The Hobbit":

Megler [1] recruited a partner to work with her on the game, Philip Mitchell [2], a fellow senior with whom she had already worked on a number of group projects and whom she knew to be both easy to get on with and a skilled programmer. Milgrom [3] himself added a third member to the team specifically to help them with the parser: Stuart Richie, who was doing a dual degree in English linguistics and computer science, with a special interest in combining the two fields.

[...]

Mitchell worked on a full-sentence parser that would allow the player to talk to the other characters in the world and even order them about. He called his system “Inglish.” Together, the code for the engine and the parser was eventually squeezed down to about 17 K, leaving the rest of the memory for Megler’s database. Richie, who was employed by Melbourne House for only a few months, contributed no code, and his ideas ultimately had little influence on the system. Milgrom’s idea of hiring a linguistics expert to develop a parser is one of those that sounds better in theory than it works in reality.

[...]

The parser is beset by problems of its own. It does understand a lot, including, for the first time anywhere to my knowledge, adverbs. It’s possible, for instance, to “viciously attack the mean goblin,” although I’d be shocked to learn that it doesn’t just throw away the adverb as it does articles. Yet in other ways, especially in early releases, it’s very frustrating to work with. It’s possible to “climb into the boat,” but not to “enter” or “get in” it; possible to ask Thorin to “carry me,” but not to ask him to “take me” (talk of randy dwarfs aside, no double entendre intended); possible to “look across the river”, but not to “look over” it.

And from an Interview with Veronika Megler (The Register, 2012):

The Hobbit stood out from the adventure games of the day in three ways, the first of which was its use of graphics. Many scenes in the game included a colour image that may have drawn at painfully slow speed but still offered a far richer experience than the text-only adventures of the day.

The second key innovation was 'Inglish', a parsing system that went far beyond the verb/noun syntax most games at the time allowed. Inglish lets players enter whole sentences of text as they sought to complete a quest that paralleled the plot of Tolkien’s famous novel.

A third and less obvious innovation was the game engine Megler created.

[...]

Analysis of the game that attributes its success to Inglish also irritate [her] just a little, as fans tell Megler that they didn't use much of the vocabulary it offered but did appreciate the ability to use different objects in imaginative ways that she [built] into the game's engine.

And finally from the Wikipedia entry:

The game had an innovative text-based physics system, developed by Veronika Megler. Objects, including the characters in the game, had a calculated size, weight and solidity. Objects could be placed inside other objects, attached together with rope and damaged or broken. If the main character was sitting in a barrel which was then picked up and thrown through a trapdoor, the player went too.

The parser was also a real-time capable, even if the player didn't enter commands, the story would move on:

Unlike other works of interactive fiction, the game was also in real time - if you left the keyboard for too long, events continued without you by automatically entering the "WAIT" command with the response "You wait - time passes". If you had to leave the keyboard for a short time, there was a "PAUSE" command which would stop all events until a key was pressed.

This was neccessary since the game's NPCs (Non-Player-Characters) and monsters were

[...] entirely independent of the player and bound to precisely the same game rules. They had loyalties, strengths and personalities that affected their behaviour and could not always be predicted. The character of Gandalf, for example, roamed freely around the game world (some fifty locations), picking up objects, getting into fights and being captured.

The game manual (Part 1 & Part 2) states that:

[the parser] knows over 500 words and can perform over 50 different actions (combining verbs and prepositions)"

The available vocabulary is quite small, though:

```<code>THE INGLISH VOCABULARY:

Movements:

NORTH (N)            NORTHEAST (NE)
SOUTH (S)            NORTHWEST (NW)
EAST  (E)            SOUTHEAST (SE)
WEST  (W)            SOUTHWEST (SW)
UP    (U)            DOWN      (D)

Action Verbs:

BREAK              FILL              SAY
CLIMB              FOLLOW            SHOOT
CLOSE              GIVE              SWIM
CROSS              GO                TAKE
DIG                KILL              THROW
DRINK              LOCK              TIE
DROP               PICK              TURN
EAT                PUT               UNLOCK
EMPTY              OPEN              UNTIE
ENTER              RUN               WEAR

Special Commands:

EXAMINE            LOOK (L)          QUIT
HELP               NOPRINT           SAVE
INVENTORY (I)      PAUSE             SCORE
LOAD               PRINT             WAIT

Prepositions:

ACROSS             INTO              THROUGH
AT                 OFF               TO
FROM               ON                UP
IN                 OUT               WITH

Adverbs:

CAREFULLY                 QUICKLY
SOFTLY                    VICIOUSLY
</code>```

For me this means, that "The Hobbit" is not so much defined by the "Inglish" parser itself (which is not that advanced by today's standards - compare the various available chat bots), but by the interplay of a for the time advanced parser with a versatile and flexible game engine.

[1] Veronika Megler, then a student in her final year as an undergraduate with an interest in database design.  Personal page: http://web.cecs.pdx.edu/~vmegler/  April 2002 Interview

[2] Philip Mitchell, recuited for Melbourne House by Veronika Megler in 1982. Also worked with Megler on Penetrator (1983). Continued to write games for Melbourne House/Beam Software until 2000. Further info: http://playitagainproject.org/creators/philip-mitchell/

[3] Alfred Milgrom, founder of Melbourne House/Beam Software (together with Naomi Besen). He hired Veronika Megler to "Make the best adventure game ever. Period." Further info: Australian Gaming Database

Body:
From The Digital Antiquarian's article on "The Hobbit":

Megler [1] recruited a partner to work with her on the game, Philip Mitchell [2], a fellow senior with whom she had already worked on a number of group projects and whom she knew to be both easy to get on with and a skilled programmer. Milgrom [3] himself added a third member to the team specifically to help them with the parser: Stuart Richie, who was doing a dual degree in English linguistics and computer science, with a special interest in combining the two fields.

[...]

Mitchell worked on a full-sentence parser that would allow the player to talk to the other characters in the world and even order them about. He called his system “Inglish.” Together, the code for the engine and the parser was eventually squeezed down to about 17 K, leaving the rest of the memory for Megler’s database. Richie, who was employed by Melbourne House for only a few months, contributed no code, and his ideas ultimately had little influence on the system. Milgrom’s idea of hiring a linguistics expert to develop a parser is one of those that sounds better in theory than it works in reality.

[...]

The parser is beset by problems of its own. It does understand a lot, including, for the first time anywhere to my knowledge, adverbs. It’s possible, for instance, to “viciously attack the mean goblin,” although I’d be shocked to learn that it doesn’t just throw away the adverb as it does articles. Yet in other ways, especially in early releases, it’s very frustrating to work with. It’s possible to “climb into the boat,” but not to “enter” or “get in” it; possible to ask Thorin to “carry me,” but not to ask him to “take me” (talk of randy dwarfs aside, no double entendre intended); possible to “look across the river”, but not to “look over” it.

And from an Interview with Veronika Megler (The Register, 2012):

The Hobbit stood out from the adventure games of the day in three ways, the first of which was its use of graphics. Many scenes in the game included a colour image that may have drawn at painfully slow speed but still offered a far richer experience than the text-only adventures of the day.

The second key innovation was 'Inglish', a parsing system that went far beyond the verb/noun syntax most games at the time allowed. Inglish lets players enter whole sentences of text as they sought to complete a quest that paralleled the plot of Tolkien’s famous novel.

A third and less obvious innovation was the game engine Megler created.

[...]

Analysis of the game that attributes its success to Inglish also irritate [her] just a little, as fans tell Megler that they didn't use much of the vocabulary it offered but did appreciate the ability to use different objects in imaginative ways that she [built] into the game's engine.

And finally from the Wikipedia entry:

The game had an innovative text-based physics system, developed by Veronika Megler. Objects, including the characters in the game, had a calculated size, weight and solidity. Objects could be placed inside other objects, attached together with rope and damaged or broken. If the main character was sitting in a barrel which was then picked up and thrown through a trapdoor, the player went too.

The parser was also a real-time capable, even if the player didn't enter commands, the story would move on:

Unlike other works of interactive fiction, the game was also in real time - if you left the keyboard for too long, events continued without you by automatically entering the "WAIT" command with the response "You wait - time passes". If you had to leave the keyboard for a short time, there was a "PAUSE" command which would stop all events until a key was pressed.

This was neccessary since the game's NPCs (Non-Player-Characters) and monsters were

[...] entirely independent of the player and bound to precisely the same game rules. They had loyalties, strengths and personalities that affected their behaviour and could not always be predicted. The character of Gandalf, for example, roamed freely around the game world (some fifty locations), picking up objects, getting into fights and being captured.

The game manual (Part 1 & Part 2) states that:

[the parser] knows over 500 words and can perform over 50 different actions (combining verbs and prepositions)"

The available vocabulary is quite small, though:

THE INGLISH VOCABULARY:

Movements:

NORTH (N)            NORTHEAST (NE)
SOUTH (S)            NORTHWEST (NW)
EAST  (E)            SOUTHEAST (SE)
WEST  (W)            SOUTHWEST (SW)
UP    (U)            DOWN      (D)

Action Verbs:

BREAK              FILL              SAY
CLIMB              FOLLOW            SHOOT
CLOSE              GIVE              SWIM
CROSS              GO                TAKE
DIG                KILL              THROW
DRINK              LOCK              TIE
DROP               PICK              TURN
EAT                PUT               UNLOCK
EMPTY              OPEN              UNTIE
ENTER              RUN               WEAR

Special Commands:

EXAMINE            LOOK (L)          QUIT
HELP               NOPRINT           SAVE
INVENTORY (I)      PAUSE             SCORE
LOAD               PRINT             WAIT

Prepositions:

ACROSS             INTO              THROUGH
AT                 OFF               TO
FROM               ON                UP
IN                 OUT               WITH

Adverbs:

CAREFULLY                 QUICKLY
SOFTLY                    VICIOUSLY

For me this means, that "The Hobbit" is not so much defined by the "Inglish" parser itself (which is not that advanced by today's standards - compare the various available chat bots), but by the interplay of a for the time advanced parser with a versatile and flexible game engine.

[1] Veronika Megler, then a student in her final year as an undergraduate with an interest in database design.  Personal page: http://web.cecs.pdx.edu/~vmegler/  April 2002 Interview

[2] Philip Mitchell, recuited for Melbourne House by Veronika Megler in 1982. Also worked with Megler on Penetrator (1983). Continued to write games for Melbourne House/Beam Software until 2000. Further info: http://playitagainproject.org/creators/philip-mitchell/

[3] Alfred Milgrom, founder of Melbourne House/Beam Software (together with Naomi Besen). He hired Veronika Megler to "Make the best adventure game ever. Period." Further info: Australian Gaming Database


问:
Best practice for comments above methods in a grails application?
I'm writing a grails application and am not sure what the best practice is with regard to comments outside of method blocks. I've done a bit of research and there seems to be conflicting views on how and when these sort of comments should be used.

In lots of source code I have seen there seems to be comments above every method detailing what that method does. I'm not sure if grails should be differnet?

My question is should I have a comment above each method in my controllers, services and domain objects?

i.e

```<code>/*
* This method displays the index page
*/
def index(){
render view : "index"
}
</code>```

答:
I dont think grails has implemeted different view for comments.

As comments are benefitial for codes as Comments ease comprehension by collecting information into one place.

It makes code understandable for developers who will need to work on the same code.
As excess comments can be load use less and precise comments.

Use comments for

When you can't use a function name to explain something

Your intent behind a decision

Clarification of code you can't alter, like library call results

Warning of consequences

TODOs (to a reasonable degree)

Amplify the importance of something seemingly inconsequential

Javadocs in public APIs


问:
How does the Scrum Master participate in Daily Stand-Ups?
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master

答:
Ideally, the scrum master is responsible for facilitating the project activities and to address any sort of impediments faced during that.
He/she does not participate in the "yesterday, today, impediments" spiel during the daily stand-up per se, however, is answerable to the team members for any kind of status on the impediments they have reported during the earlier stand-ups.

I have worked with 5 scrum teams with a reputed organization, all of them followed the same practice.

To get a detailed picture of all the responsibilities of a scrum master, I recommend you have a look at this http://www.scrummasterchecklist.org/pdf/ScrumMaster_Checklist_12_unbranded.pdf


问:
Is explicit else needed in initialisers?
I have a custom designated initialiser like this:

```<code>- (id)initWithLocation:(CLLocation *)location
{
    if (location == nil)
    {
        return nil;
    }

    self = [super init];

    if (self)
    {
        self.location = location;
    }

    return self;
}
</code>```

My colleagues sometimes ask me to wrap everything (apart from the return), that follows after first curly brace pair, in an else clause:

```<code>- (id)initWithLocation:(CLLocation *)location
{
    if (location == nil)
    {
        return nil;
    }
    else
    {
        self = [super init];

        if (self)
        {
            self.location = location;
        }

        return self;
    }
}
</code>```

But I am not sure. What is the point? The first if condition is a quick death check. If the parameter is not provided, no instance is provided. This serves as enforcement for providing a parameter. else seems superficial here as it is implied in the flow of the code.

What would be the advantage having it?

答:
The additional else statement will have no impact on logic or performance. But it still has its advantages.

First of all, it will increase readability by showing a clear chain of decisions. Going further, you could declare a variable in the beginning of the initializer to hold the return value. Then in the main part you could edit the variable and/or assign it a new value. The last line would be the return statement. This will increase readability even more.

Another advantage is that the if\else design allows you to track the mutual-exclusive options. If you'll need to add another option, such style will help you to quickly place it in the right place without additional code changes and without a risk of errors while implementing the new logic.


答:
What would be the advantage having it?

None whatsoever, in my opinion. It adds an unnecessary level of nesting while it shouldn't be hard to interpret the "fail fast" if (foo == nil) return statement(s) on top of a method.

Title: Is explicit else needed in initialisers?

Body:
I have a custom designated initialiser like this:

```<code>- (id)initWithLocation:(CLLocation *)location
{
    if (location == nil)
    {
        return nil;
    }

    self = [super init];

    if (self)
    {
        self.location = location;
    }

    return self;
}
</code>```

My colleagues sometimes ask me to wrap everything (apart from the return), that follows after first curly brace pair, in an else clause:

```<code>- (id)initWithLocation:(CLLocation *)location
{
    if (location == nil)
    {
        return nil;
    }
    else
    {
        self = [super init];

        if (self)
        {
            self.location = location;
        }

        return self;
    }
}
</code>```

But I am not sure. What is the point? The first if condition is a quick death check. If the parameter is not provided, no instance is provided. This serves as enforcement for providing a parameter. else seems superficial here as it is implied in the flow of the code.

What would be the advantage having it?


答:
It can be hard to reconcile push models with separation of concerns.  Loose coupling, generally seen as good practice, means designing the components of your system with minimal dependencies and the least possible knowledge of the overall structure and other components.  Push semantics either break this (if implemented simplistically) or add significant complexity (c.f. the observer pattern); either way, at least one component needs good knowledge of all of its dependants to implement the push.

Maintaining a loose coupling between components in an event-driven system requires a corresponding increase in the complexity of the overall system and can, perversely, tightly couple each component to the semantics of the event model.  This can make it hard to extend or alter the model, so that the system designers find they have simply swapped one set of constraints for another.  Pub/Sub mechanisms (e.g. Message Queues) are very prone to this but it is a general problem.

For simple real-world examples look at e-mail.  SMTP mail delivery is a push model; it is very robust, but has proved very difficult to extend to deal with unforeseen scenarios (spam would be the classic example, but also look at the problem that ETRN and ATRN were developed to address, and how partially and inconsistently those were adopted).  Look at how much more complex SMTP is than POP or even IMAP (both essentially pull models) and how much more work had to go into making it resilient.

Historically, the complexity surrounding push mechanisms made them harder to implement.  Our capacity for this complexity has increased over time.  However, event-driven systems have their own pitfalls.

I would question your assertion that all the domains we model are changing rapidly.  The context in which we use them may become more complex (and richer), but some problems stay simple.  Loose coupling is one of the ways we limit the necessity to change individual components as the system around them changes.

Title: history and application areas of 'pull'/'push' programming paradigm

Body:
Recently reading a lot materials on Reactive Programming, one thing frequently mentioned is the 'PUSH' versus 'PULL' style of application.  Event driven ( Reactive programming )

Some of the authors say that both these styles have their area of applications, but aren't most application domains we are trying modeling are all changing rapidly in real world and thus  event driven is more appropriate?

And why we started from the 'PULL' approach and now turning into 'PUSH' approach, are there specific reasons causing the change?


问:
How to level up as a PHP developer
I've been doing PHP for 4 years now. 2 years at school and 2 years at work.
But I feel like I'm stagnating. Here are some things that I currently know about PHP:

Basics (variables, control structures, arrays, loops, sessions, cookies, file manipulation)

Database Integration (MySQL)

OOP - I only know of the basics (creating classes, inheritance, objects, private, public and protected class variables)

MVC

A few frameworks (CodeIgniter, Laravel)

PHPUnit (Assertions)

Templating (Smarty)

Using PHP with AJAX

Building Wordpress plugins

API Integration

That's pretty much it. My question is what's next? What do I do to level up my skills as a PHP developer. What are the things that you can recommend that I would do in order to improve (Books, tutorials, etc.). What other PHP tools you can recommend that I should try and use.

Thanks in advance!

答:
Learn some other languages.  Every time you see another implementation of a concept you know from one language, it'll teach you more about the essential concept, how good/bad the implementation is in your language of choice and how best it is used.  You'll also encounter entirely new concepts.

This is particularly true of OOP, but goes for all the concepts outlined above.

Forgive me for saying that PHP's implementation of many of the above is substandard.

Title: How to level up as a PHP developer


问:
What is the difference between string.c_str() and &string[0]?
What are the differences between string.c_str() and &string[0]?

Regarding performance my guess is that &string[0] is a little faster than string.c_str() as it doesn't require a function call.

Regarding safety and stability common sense tells me that string.c_str() should have some checks implemented, but I don't know, that's why I'm asking.

答:
In C++98 there is no guarantee that the internal array is null terminated; in other words string.data()[string.size()] results in undefined behavior. The implementation will then reallocate the array with the null termination when c_str() is called but can leave the null terminator off when it isn't.

This also means that &string[0] is not guaranteed to be null terminated (it is essentially a detour to data())

In C++11 the null termination guarantee is specified so string.data()==string.c_str() is always valid.


问:
Should we be completely honest to our clients about a time frame for a project?
I have been having this experience for sometime now, when a client needs a software product and contacts me, the client usually wants to know the time frame on which this product will be accomplished. Usually as a software developer I might not be able to fully determine how long it will take me to finish the job since I may encounter an error that may take me weeks (sometimes months) to solve.

If I tell the client the expected time frame based on my analysis i.e. no matter how bad it gets, I should be able to finish the job in lets say 6 months maximum (for example). My client usually says NO! six months is too long, I need it urgently, maximum should be one month. If I refuse to accept the time frame given by the client he may give the contract to another developer who accepts the short time frame of the client and yet does not execute the job in time.

On the other hand, if I accept the short time frame of the client and get the contract (knowing fully well that it will be impossible to finish it in time), I will only succeed in getting the contract and then later come up with excuses as to why the job is not completed in time. This now seems to be a norm, but deep down I feel I am learning how to be dishonest in order to get contracts. So is it a bad thing or is it just a business strategy?

答:
Based on the scenario you gave, I question whether the client is being honest with you or the other company. You say it takes six months, but they want it in one. There are excuses for the incomplete project, but the client pays anyway or now they're able to delay it? Something doesn't add up or the client has a loose interpretation of what urgent means.

Both sides seem to be playing a game. Developers pad their estimates and clients arbitrarily set shorter due dates because they know developers exagerate how long things take to build. We haven't even gotten to scope creep yet.

Personally, I avoid dealing with clients in this way. A huge discrepancy in project estimates means something is very wrong. Take the project into smaller parts and give estimates for those. This may give the client a better idea of what is required and the amount of time to do them properly. These can be adjusted and many difficult to estimate projects need some initial trail and error. Your competition may not be dishonest, but unaware of what it takes or maybe they're throwing more devs at the problem, have experience in this area along with some boiler-plate/prefabricated code already in place.


答:
You should reason with these types of clients in situations like this.

Instead of giving a single time-frame from start to finish, explain to them that you can have a somewhat production-ready tool in a span of one month.

If you explain to them (using like a piece of paper) the algorithm or steps involved in producing a software product, this will make them understand what software development is. Knowing how people generally may be towards this, you need to highlight the important parts of the production process.

For example:

Explaining how design requires some time to plan, to ensure that the site is both beautiful and drives more sales/leads for the client

Explain the aspect of security, as this will matter to site-users, so clients should ensure that their sites are secure (in situations where this is needed)

Explain about SEO, etc.

I don't think you should charge a fee for explaining this process, unless you can get it done within the allotted time that they're paying for.

The gist of what I'm trying to say is that you need to explain to clients in a way that they can see benefits directly to themselves.

If I ran (for example) a shoe retailing business, the things I'd like to hear most from a software developer is how their work will benefit my business, which is what you need to do.

You can lastly, also explain to them why it is impossible to achieve a good final product in a span of one month.

Then let them decide, based on all the facts you've given, if it is acceptable to have a half-baked product in one month instead of a better solution in a little longer time (also, 6 months is a very long time. You should think of trying to reduce this time to a maximum of 2-3 months, unless you deliver a rolling-product in which a working version is available soon, but you keep updating it until it is production-ready).

Title: Should we be completely honest to our clients about a time frame for a project?

Body:
I have been having this experience for sometime now, when a client needs a software product and contacts me, the client usually wants to know the time frame on which this product will be accomplished. Usually as a software developer I might not be able to fully determine how long it will take me to finish the job since I may encounter an error that may take me weeks (sometimes months) to solve.

If I tell the client the expected time frame based on my analysis i.e. no matter how bad it gets, I should be able to finish the job in lets say 6 months maximum (for example). My client usually says NO! six months is too long, I need it urgently, maximum should be one month. If I refuse to accept the time frame given by the client he may give the contract to another developer who accepts the short time frame of the client and yet does not execute the job in time.

On the other hand, if I accept the short time frame of the client and get the contract (knowing fully well that it will be impossible to finish it in time), I will only succeed in getting the contract and then later come up with excuses as to why the job is not completed in time. This now seems to be a norm, but deep down I feel I am learning how to be dishonest in order to get contracts. So is it a bad thing or is it just a business strategy?


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答:
Understand the general principles of security, (integrity, authentication, authority) and then
read a few books about how people have been subverting these pillars of security for millennia and you will be about half way there.

Then read a few good books on design and testing strategies and you will learn how to design testability into your architecture.

Now we get to the point when I do think about security. I am thinking about how can I validate the data source, does it matter if the data is tampered with, who is the data source, how sure of that am i? how could it have been altered etc...

This affects the design.  Config files may have key sections encrypted, or particular fields could be in clear text with an associated signature field.  Things get more complex with internet facing services as you should expect a greater level of hostility there.

Then at testing, how do you test all this.  What are your maximum data entries, what happens if you push the software beyond those limits, how does it handle it?  What does it trust?  how can you fake that trust?


答:
I think that what you and your colleague are discussing is expressing intent within your code.

There are two broad cases that we need to consider to answer your question.

Guard checks

Separation of application logic / conditional branching

Guard Checks

Your example demonstrate the first case - a guard check.  A guard check inspects inputs or other requisite inputs to make sure things are valid.  If things aren't valid then the function needs to immediately exit or return.

The conventional wisdom that I have encountered is that guard checks don't really count as part of the logic of your function.  An experienced programmer skimming your code would take note of the guard checks and then start paying attention at the initialization step in your example.

So in the case of the guard checks, you don't really need the else {} block to clearly express the intent of your function.

Conditional Branching

The other case when there is extensive application logic requires a different consideration in order to express intent.  The simplified version looks like this:

```<code>if( A )
{
    ...
    doFoo()
}
else
{
   doBar()
}
</code>```

Concerns about expressing intent now revolve around how much code those ellipses represent.  If it's "a lot" of code, then your colleague is correct and you need to wrap the not A branch with an else statement and potentially its own set of braces.  The thinking here is that you don't want future maintainers to have to deal with too much mental overhead while trying to understand your function.  The else clearly demonstrates you have two main paths.

So to answer your question, you have to ask which option more clearly expresses your intent as the developer of the code.

Body:
I think that what you and your colleague are discussing is expressing intent within your code.

There are two broad cases that we need to consider to answer your question.

Guard checks

Separation of application logic / conditional branching

Guard Checks

Your example demonstrate the first case - a guard check.  A guard check inspects inputs or other requisite inputs to make sure things are valid.  If things aren't valid then the function needs to immediately exit or return.

The conventional wisdom that I have encountered is that guard checks don't really count as part of the logic of your function.  An experienced programmer skimming your code would take note of the guard checks and then start paying attention at the initialization step in your example.

So in the case of the guard checks, you don't really need the else {} block to clearly express the intent of your function.

Conditional Branching

The other case when there is extensive application logic requires a different consideration in order to express intent.  The simplified version looks like this:

if( A )
{
    ...
    doFoo()
}
else
{
   doBar()
}

Concerns about expressing intent now revolve around how much code those ellipses represent.  If it's "a lot" of code, then your colleague is correct and you need to wrap the not A branch with an else statement and potentially its own set of braces.  The thinking here is that you don't want future maintainers to have to deal with too much mental overhead while trying to understand your function.  The else clearly demonstrates you have two main paths.

So to answer your question, you have to ask which option more clearly expresses your intent as the developer of the code.


答:
If you don't know what to work on, pick up an interesting book. If you don't know what to read, start working on an interesting project. Do something. In the process of reading or working, you'll encounter things you don't know or things that you find interesting, and you can follow those threads to expand your horizons.

The dictionary says that to stagnate is to cease developing; become inactive or dull. If you don't want to stagnate, do the opposite: Be active. Learn things. Make things. Exactly what things you should learn or make are entirely up to you, and nobody here can tell you what they should be.

If your goal is simply to not stand still, then it doesn't really matter what you do provided it's something new or different. But you probably want to do more than just move, you want to move in a particular direction. Decide on a goal -- the place where you want to be in 6, 12, or 18 months. What skills do you need to reach that goal? Write them down. Choose activities that will help you develop those skills, and cross each skill off your list as you acquire it to help you chart your progress toward your goal.

Title: How to level up as a PHP developer

Body:
I've been doing PHP for 4 years now. 2 years at school and 2 years at work.
But I feel like I'm stagnating. Here are some things that I currently know about PHP:

Basics (variables, control structures, arrays, loops, sessions, cookies, file manipulation)

Database Integration (MySQL)

OOP - I only know of the basics (creating classes, inheritance, objects, private, public and protected class variables)

MVC

A few frameworks (CodeIgniter, Laravel)

PHPUnit (Assertions)

Templating (Smarty)

Using PHP with AJAX

Building Wordpress plugins

API Integration

That's pretty much it. My question is what's next? What do I do to level up my skills as a PHP developer. What are the things that you can recommend that I would do in order to improve (Books, tutorials, etc.). What other PHP tools you can recommend that I should try and use.

Thanks in advance!


答:
Do not lie.  It will only bite you in the end.  You will feel much happier doing contracts that are reasonably framed where you aren't fighting the client and your dishonest estimates all the way.  After all, the real work happens after the estimates.  You'll lose some contracts at first to lowballers, but those customers will come to you after those lowballers overrun their estimates.  You'll build up trust and good customers that way.

Do not try to guesstimate the "absolute worst case" as you seem to suggest you do in the question.  The absolute worst case is unpredictable - instead estimate something like "75% chance of finishing in X time" - 100% is impossible - 95% will take much longer and is much less likely than 75%.  Doing it like this means that 1 out of 4 projects will have an overrun - that still means 3 out of 4 projects will come in on-time with happy clients, and that fourth one probably has very good explanations why it's late.

Get "Software Estimation: Demystifying the Black Art" - you'll learn a lot, even if it's only to confirm that nobody really knows :P

Be very, very careful with clients that come to you with an "urgent" project.  That "urgent" project is already late.  Success is unlikely because there are two much more likely outcomes that aren't "external person saves the day": the further lateness of the project caused by your development time will be redirected at you (i.e. in their eyes it will become your fault they are late), OR during the time it takes you to develop the project they will find an alternative solution and you'll have trouble getting paid for your work because they don't need it anymore.


答: Yes. When I worked on a multiplayer game, all were paranoid of exploits and ways to cheat. Cheating can destroy a game totally, not to mention any business models connected to selling in-game stuff. So security concerns and anti-tampering measures were very high on the agenda. I liked it very much. I have worked on others projects before where you had to feel guilty for working longer on the code just to assure it was secure.</p>

Title: Do you actively think about security when coding?

Body: When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>


问:
How to approach multiple page form with just one save option
The screen shot shows the magento product upload page.

The left nav allows you to switch to different options for the product. Basically each option in the left nav appears as a different page. However when you save and close, it will save all the updates made on each page.

Using Foundation4, html, css, js - what would be the best approach to replicating something similar? Say I want 3 pages and one save button option.

Using http://foundation.zurb.com/docs/components/section.html#panel2 and having the save buttons the top line form level seems a possible option.

答:
As mentioned by @codingstill, Tabs will do. But from the users perspective its not a good design.

It depends on the user. If a user doesn't have much experience with the web then he/she might not know that the form will be saved even if you move to different tabs. or they might click save everytime before moving between tabs.


问:
How important are code formatting guidelines?
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.

答:
I think there's an unmentioned benefit in helping to quickly understand code.  The more similar that code formatting is across a project and all developers, the easier (and more subconsciously) you'll be able to work with the code.

I've had junior developers come to me after trying to deal with even simple bugs for an extended period of time. After taking a few minutes to apply our code format with them, they were quickly able to see the bug that they had missed before.

While readability is definitely important.  If your code format standards are well thought out, and are properly used, you may find that you can go beyond just being able to read the code, and to being able to understand the code even quicker.

One set of guidelines I use when developing or updating our coding formats is the Gestalt Principles of Grouping - http://en.wikipedia.org/wiki/Gestalt_psychology#Gestalt_laws_of_grouping

As a direct result/example our code formatting requires that any block code (if, switch, etc.) has the open brace on the next line, so that it lines up with the closing brace:

```<code>if(true)
{
}
</code>```

With the reasoning that by the Principle of Symmetry, your mind will see the open and closing braces and more quickly be able to perceive the code block naturally.

Body:
I think there's an unmentioned benefit in helping to quickly understand code.  The more similar that code formatting is across a project and all developers, the easier (and more subconsciously) you'll be able to work with the code.

I've had junior developers come to me after trying to deal with even simple bugs for an extended period of time. After taking a few minutes to apply our code format with them, they were quickly able to see the bug that they had missed before.

While readability is definitely important.  If your code format standards are well thought out, and are properly used, you may find that you can go beyond just being able to read the code, and to being able to understand the code even quicker.

One set of guidelines I use when developing or updating our coding formats is the Gestalt Principles of Grouping - http://en.wikipedia.org/wiki/Gestalt_psychology#Gestalt_laws_of_grouping

As a direct result/example our code formatting requires that any block code (if, switch, etc.) has the open brace on the next line, so that it lines up with the closing brace:

if(true)
{
}

With the reasoning that by the Principle of Symmetry, your mind will see the open and closing braces and more quickly be able to perceive the code block naturally.


问:
Are Interfaces with Java 8 Virtual Extension Methods the Same Thing as Mixins?
This post describes a new feature in Java 8 called virtual extension methods (formerly called default methods, or defender methods). In the example provided, an interface has one method, which is implemented by a class. Then a second method is added, but instead of forcing the class to immediately implement the interface's new method, a "virtual extension method" is created within the interface as an implementation of this new method, thus the class doesn't need to implement the new method right away.

But say that the programmer decides to create a virtual extension method in an interface and never plans to have subclasses implement its own version. Wouldn't that be a mixin? It seems like one to me, but I've never heard it referred to as such. Is there some fundamental difference that I'm not understanding?

答:
Yes, these are mixins.  They aren't as powerful as Scala traits (no ability to have a reference to the parent "self" object and its properties or methods), but the default methods can implement meaningful behaviour and so can be more more than sticking plasters to stop existing code breaking when an interface is extended.

The limited power of default methods seems to be deliberate, judging by the various informed discussions of the feature.  The designers' advice is that default methods should generally not contain the concrete implementation of a method but accept a lambda or reference to a concrete class, either of which can provide the implementation. Example here


答: It's similar to a mix-in but not as powerful since an interface can't contain data.</p>

Title: Are Interfaces with Java 8 Virtual Extension Methods the Same Thing as Mixins?

Body:
This post describes a new feature in Java 8 called virtual extension methods (formerly called default methods, or defender methods). In the example provided, an interface has one method, which is implemented by a class. Then a second method is added, but instead of forcing the class to immediately implement the interface's new method, a "virtual extension method" is created within the interface as an implementation of this new method, thus the class doesn't need to implement the new method right away.

But say that the programmer decides to create a virtual extension method in an interface and never plans to have subclasses implement its own version. Wouldn't that be a mixin? It seems like one to me, but I've never heard it referred to as such. Is there some fundamental difference that I'm not understanding?


问:
Automating tests in a browser not supported by selenium
I work on a company that have a payment system that runs under a executable kiosk instance of internet explorer 7. when the application is running the process name is not similar with iexplore.exe or something like that.

The name of the windows process is the same as the executable.exe.

We cannot  run the system under a local webserver because the executable expect  some pages in pure .html to process the data and give the users change. The executable pass information to the .html forms and vice-versa. So we cannot user another browser.

I think selenium will not work with this browser. Any idea how i can automate tests on the interface?

EDIT

Selenium fail trying to start my executable:
Exception: Failed to start new browser session: org.openqa.selenium.server.RemoteCommandException: Error while launching browser

I think the executable its not the browser itself. Its just a executable that make some security tasks and after that call a internet explorer instance somehow. But the internet explorer process don´t appear on the windows process.

答:
You could try other automated browser drivers like Watir or Sahi. Selenium is kind of the benchmark for browser automation, but other tools could work better in different circumstances. </p>

<p>That being said, one thing I'd always recommend when it comes to UI testing is good old manual testing of the app. Exploratory techniques might work well here, but usually it's best to start out with a real human being looking at the UI first and then deciding what role automation should play. </p>

Body:
You could try other automated browser drivers like Watir or Sahi. Selenium is kind of the benchmark for browser automation, but other tools could work better in different circumstances.

That being said, one thing I'd always recommend when it comes to UI testing is good old manual testing of the app. Exploratory techniques might work well here, but usually it's best to start out with a real human being looking at the UI first and then deciding what role automation should play.


问:
How much difference does experience make?
I see many job adds which require at least x years experience. The question is how do you know when a candidate has the required years of experience? What do you expect from a person with x years experience (edit: effectively how do you check if the CV isn't lying without relying to skill checking)? What can a person with x years experience can do that one with y years (with y < x) cannot do (edit: assuming they have similar skills)?

There can be cases with some passionate programmer with y years experience that has vast knowledge and worked on multiple projects and other programmer with x years experience (x > y) that has worked on few projects and doesn't have that much experience.

Why can not it be reduced to something like this "if you know this technology and you know how to do that stuff (be it design, communication, estimates etc.) then you are suitable for our job"?

I know you cannot hire a fresh graduate with 1 year experience for the post of an enterprise architect but I also see a problem with the facts that almost all ads ask experience. IMHO firstly passion should be taken into account.

Firstly I did not know if the question is suitable for this site but since there is a tag for recruiting and experience I believe it has a place here.

答:
I will answer this by addressing each of your questions in the post.

The question is how do you know when a candidate has the required
  years of experience?

This is normally what the interview process aims to filter out. Multiple interviews are conducted and you can normally evaluate a candidates experience against some of your own in-house developers.

What do you expect from a person with x years experience?

You would expect them to fulfil the job requirements that are specified in a job post. For example:

"We are looking for a senior PHP developer with 10+ years experience working in system design and architecture to restructure our system tools as the Chief architect, whilst managing K amount of senior and junior developers and guiding them along the way. The job will also require... (etc. etc.)"

What can a person with x years experience can do that one with y years
  (with y < x) cannot do?

You're looking at experience wrong in this case. Job posts don't only ask for number of years, but also experience in the technologies that the company is using. Like you could have 10 years experience in C++ development, and say I am a gaming company looking for C++ developers with even 5 years experience. You still wouldn't be my ideal candidate because you've never worked in the gaming industry before. My job post would actually specify: X amount of years experience in A, B, C aspects of programming.

There can be cases with some passionate programmer with y years
  experience that has vast knowledge and worked on multiple projects and
  other programmer with x years experience (x > y) that has worked on
  few projects and doesn't have that much experience.

Read my previous answer. Experience is tied to the tools you're experienced in. X amount of years in A, B, C tools.

Why can not it be resumed to something like this "if you know this
  technology and you know how to do that stuff (be it design,
  communication, estimates etc.) then you are suitable for our job"?

This can and does happen. If you can prove yourself then experience in years doesn't matter. For a guy like yourself, you seem more suited to a smaller dev shop, where the interviewer/recruiter is a developer him/herself. Bigger companies normally have HRs doing this type of stuff, which is why they make the job requirements so broad that you basically need a PhD with 15+ years experience to write small functions for their website (over-exaggeration but it kind of explains the flaws in programmer recruiting, especially for the bigger companies - although not all of them suffer from this ailment)


答:
"Years of experience" is more of a probability scale than a measure of anything concrete. With more years in, you get an increased chance that a person has encountered things such as:

Has participated in a crisis-like event.

Has seen a project from beginning to end.

Has seen a project fail to begin or end.

Has worked on legacy code.

Has worked on a blank slate and made something.

Has implemented design decisions.

Has designed a system.

Has written a bug, released a bad fix, taken down a server; Has screwed up, essentially.

Has fixed a screw-up.

Has found the weird edge cases in the language they work in, and seen a place where they matter.

Has learned that things currently in the codebase might be dumb.

Note, these things are a small, non-mandatory sample, and also include dozens of little things that can be found working in a live environment.

Again, it's a chance thing, and it depends entirely on /where/ they got those years of experience. One person could have worked in a single project on a team of several hundred people and become highly specialized. Another could have been in a trial-by-fire small shop, and become more of a generalist as they deal with servers/installation/coding/QA/DBA/project management. There's also people who find themselves getting the same year of experience over and over again.

It's a rough measure, but on average a person will have been exposed to more potential learning events the longer they've been working, and it's useful as a preliminary data point. The rest of the resume (and more importantly the interview) are for figuring out what they actually know, and what they've actually done.

Title: How much difference does experience make?

Body:
I see many job adds which require at least x years experience. The question is how do you know when a candidate has the required years of experience? What do you expect from a person with x years experience (edit: effectively how do you check if the CV isn't lying without relying to skill checking)? What can a person with x years experience can do that one with y years (with y < x) cannot do (edit: assuming they have similar skills)?

There can be cases with some passionate programmer with y years experience that has vast knowledge and worked on multiple projects and other programmer with x years experience (x > y) that has worked on few projects and doesn't have that much experience.

Why can not it be reduced to something like this "if you know this technology and you know how to do that stuff (be it design, communication, estimates etc.) then you are suitable for our job"?

I know you cannot hire a fresh graduate with 1 year experience for the post of an enterprise architect but I also see a problem with the facts that almost all ads ask experience. IMHO firstly passion should be taken into account.

Firstly I did not know if the question is suitable for this site but since there is a tag for recruiting and experience I believe it has a place here.


问:
Mixed licenses inside product
This question relates to software-licensing. Someone familiar with open-source licensing may be able to answer this question.

I am facing an issue in trying to interpret/understand some Licenses, due to a language barrier (English is not my first language). My situation is that I am using three products inside a distributable closed-source commercial product. These are:

Jersey (Common Development and Distribution License)

Jetty (Dual Apache & Eclipse)

RXTX (LGPL)

The tools above are not modified in my project and are used 'as is' included with Maven.

My question is what step/s should I take to be perfectly sure I am not violating any Licence agreements?

Should I (for example):

Put some information inside the README file that I am using this software inside?

Print something in command line?

Should I place the full-license texts of those tools in separate files (but this could be misleading to customer, because my product doesn't have any Licence)?

Could I extract these Licenses text files during the first JAR run?

I am looking for practical information, not necessarily from a lawyers.

答:
You need to talk to a lawyer about this. A lawyer who specializes in "IP law."

I am not a lawyer. What I am about to say is probably wrong, because I do not have a complete understanding of your project, nor about the interaction of the CDDL with the LGPL.

However, I can tell you some of what each license requires:

Jersey's license, the CDDL, requires that you:

make available all source code under that license to your end users;

include a copy of the CDDL license text with your distribution;

make notice of all changes you made to Jersey (this can be done in the source code distribution in the form of comments and/or as a README);

ensure that your proprietary license does not conflict with the CDDL.

You must choose which of Jetty's two licenses you will comply with (including the additional exceptions listed in the NOTICE file). Both licenses require that you:

must include the full text of both the licenses and the NOTICE file;

must make available the source code if you made changes or point to where end users can get the source code if you did not;

ensure that your proprietary license does not conflict with either Apache or Eclipse.

It must be possible for users to replace RXTX with their own compiled version of RXTX in order t ocomply with the LGPL. You must also:

include the full text of the LGPL and any other NOTICE or attribution files;

make available the full source code of the LGPL'd code;

ensure your own license does not conflict with the terms of the LGPL as it applies to RXTX.

You should also draft (with the help of an attorney) clear terms for your end-user license agreement. This license should make it clear that portions of the project are open source and under various different licenses. Your attorney must make sure your license does not conflict with any of the terms of the other licenses.

Lastly, you should not ask for legal advice on a forum such as this, for a topic that is mired in so many legal potholes.

OwnerDisplayName: flyer

Title: Mixed licenses inside product


问:
How to get a job with no experience?
I am about to be a new college grad and I am trying to get an internship or a jr software engineer position. However, I have no experience at all in the field.

All I will have is my degree and my in class projects that I have completed. How can I make my resume more attractive so that I can get an interview? Also, how should I structure the details of my in class projects? Should I provide extensive detail?

答:
One thing I'll tell you is that colleges have a tendency to not teach very much at all in their CS degrees, compared to what they should. As in, you really need about two or three times the technical expertise that you will get in a basic CS Bachelor's to fully know what you're doing as a programmer. Some people study or work extracurricularly, which helps a lot, but core classes alone are a limitation.

...So what will set you above other candidates?

Knowing at least a few more languages than they teach you in college, as well as how to integrate a database into a program.

Be experienced enough to no longer be "green".

You would do well to put together the following:  Make a web service whose implementation is in .Net, and which uses an instance of SQL server.  Make a web site with a scripting language that makes calls to that web service to store and retrieve information in the database.  Make sure you can use that web site over the Internet, and not just with your own computer or office LAN.  It's fine if the site's small, but make sure it does something useful.  If you put in enough research, coding, testing, debugging, etc. to actually do something like this, that ought to impress an employer.

Title: How to get a job with no experience?


问:
Are Language Comparisons Meaningful?
Dr Bjarne Stroustrup in his book D&E says

Several reviewers asked me to compare C++ to other languages. This I have decided against doing. Thereby, I have reaffirmed a long-standing and strongly held view: "Language comparisons are rarely meaningful and even less often fair" . A good comparison of major programming languages requires more effort than most people are willing to spend, experience in a wide range of application areas, a rigid maintenance of a detached and impartial point of view, and a sense of fairness. I do not have the time, and as the designer of C++, my impartiality would never be fully credible.

-- The Design and Evolution of C++(Bjarne Stroustrup)

Do you people agree with his this statement "Language comparisons are rarely meaningful and even less often fair"?

Personally I think that comparing a language X with Y makes sense because it gives many more reasons to love/despise X/Y :-P

What do you people think?

答:
That, except in some rare (and - rare - as in "it happens once or twice in the lifetime of a solar system") exceptions, it usually leads to language wars, in more or less strong variant, and very rarely leave some practical and useful conclusions.

Languages are tools, not religions. You don't compare a hammer with a screwdriver, but you use the one that fits your task & way of thinking/education/needed level of abstraction the most.
Also, since the one doing the comparison is biased by the fact that he knows at least one of the two, or at least prefers one of the two, it is hard to find a truly objective criteria for comparing them (exceptions exist).

Title: Are Language Comparisons Meaningful?


问:
Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?
A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?

答:
I'm not sure this is the best rule of thumb out there. You can put an abstract method in the base class and have each class implement it. Since every mammal has to eat it would make sense to do that. Then each mammal can use its one eat method. I typically only use interfaces for communication between objects, or as a marker to mark a class as something. I think overusing interfaces makes for sloppy code.

I also agree with @Panzercrisis that a rule of thumb should just be a general guideline. Not something that should written in stone. There undoubtedly will be times where it just doesn't work.


问:
Interface at the class or function level?
I have been falling into a pattern lately where I have been defining routines that rely on an interface defined by a function that is specified as a parameter to the routine. (The language is C#, but this can be applied to any language with first-class functions.)

For example, I have an API that exposes CRUD operations against a backing store. In the case of a GET operation on a particular resource, I can generalize the routine into:

get the resource we are looking for

return a not found response if resource does not exist

return the resource if found

What I ended up doing is defining a routine that accepts a delegate function for finding the resource. It's this delegate that defines the interface contract.

This happens to work well for my situation because the information required to locate the resource can vary. In my case, it's looking up data in a database by keys, but the type and number of keys can vary. I can capture these in a closure in the calling routine and satisfy the delegate function interface. For example:

```<code>// Locate a simple record that only has one key
public SimpleRecord GetSimpleRecord(int recordID) {
   return getResource(repository => repository.SimpleRecords.Find(recordID));
}

// Locate a complex record that has many keys
public ComplexRecord GetComplexRecord(int recordID, int userID, string token) {
   return getResource(repository => repository.ComplexRecords.Find(recordID, userID, token));
}
</code>```

This work, but seems like is a mix of OOP and functional style programming. If I need more than one delegate passed, it starts to get a bit messy. Some routines that I need everywhere I ended up defining as abstract methods that all sub-classes need to implement. So I have a hybrid.

Does this type of technique have a name or pattern that I'm missing? Should the delegates be implemented in a defined class interface that gets passed to the caller?

UPDATE with more concrete example:

I'm trying to adhere to the DRY principal. I'm talking about controllers in a C# Web API application. Each and every request has some commonality which I have implemented in a base controller class:

Handle all exceptions by returning the correct HTTP status code, (404 for resources that are not found, 201 for created resources, etc.)

Map database entities to-and-from data transport objects that the client deals with

I want to express what to do in this base class, and delegate how to the concreate class. The how ends up being implemented by delegate functions. I may need to get a person from the database, by first name and last name, or a purchase order, by an integer id. In both cases, if the resource is not found, a 404 must be returned. One returns a person, one a purchase order. How to look them up and how to map the data to a client object differs.

The base function may look like this:

```<code>T getResource<T> (Func<IRepository, T> find) {
    T data = find(getRepository());
    if (data == null) {
        throw new DataNotFoundException();
    }
    return data;
}
</code>```

Now, in the person controller and purchase order controller, I don't have to repeat the logic of what do to when the resource is not found--just implement the find delegate. (This is a simple example without mapping, adding, removing or other details that differ resource to resource).

```<code>public Person Get(string first, string last) {
   return getResource<Person>(repository => repository.People.Find(first, last));
}

public PurchaseOrder Get(int id) {
   return getResource<PurchaseOrder>(repository => repository.POs.Find(id));
}
</code>```

Note how the closures above neatly deal with varying number and types of parameters for finding things, but satisfy the interface defined by the delegate find function. Is this possible to do with standard class interfaces?

(And this question is not about the repository. That is resolved with dependency injection and is implemented with Entity Framework.)

答:
You might have more indirection than you need.  For example:

```<code>public SimpleRecord GetSimpleRecord(int recordID) {
   return getResource(repository => repository.SimpleRecords.Find(recordID));
}
</code>```

could simply be:

```<code>public SimpleRecord GetSimpleRecord(int recordID) {
   return repository.SimpleRecords.Find(recordID);
}
</code>```

Assuming that Repository fulfills an interface contract like IRepository, you can simply inject a repository that draws from the correct data source.

```<code>public class DataAccess
{
    IRepository repository;

    public DataAccess(IRepository repository)
    {
        this.repository = repository;
    }

    public SimpleRecord Find(int recordID)
    {
        // etc.
    }
}
</code>```

Body:
You might have more indirection than you need.  For example:

public SimpleRecord GetSimpleRecord(int recordID) {
   return getResource(repository => repository.SimpleRecords.Find(recordID));
}

could simply be:

public SimpleRecord GetSimpleRecord(int recordID) {
   return repository.SimpleRecords.Find(recordID);
}

Assuming that Repository fulfills an interface contract like IRepository, you can simply inject a repository that draws from the correct data source.

public class DataAccess
{
    IRepository repository;

    public DataAccess(IRepository repository)
    {
        this.repository = repository;
    }

    public SimpleRecord Find(int recordID)
    {
        // etc.
    }
}


答:
A language is a tool. That said, I've seen really, really crappy tools before. No one wants to work with a hammer whose head is liable to fly off and hit another carpenter in the stomach. Likewise, if you noticed your fellow worker's hammer was in that shape, you'd probably steer clear of them when they were using it.

It's also important to really understand which tool it is. You can't use a screwdriver and hammer interchangeably (though some try desperately). Hell you can't even use all hammers interchangeably; you need a sledge for some things, a mallet for others and a tack for yet others. If you use the inappropriate tool, then at best, you'll do a poorer job, at worst you'll injure yourself or a co-worker.

In other words, language comparison is useful in that it can prevent workplace accidents. Taking the above out of metaphor; it's difficult to know without comparing whether a given language is a sledge hammer, a screwdriver, a dremel or a table saw, because (unlike with physical tools) you can't really tell just by glancing. You need to think about the features it offers, see it in action (by trying to read significant pieces of a large codebase written in it), and ideally, test-drive it yourself too. Careful not to make the mistake of just writing Cobol in Python (for example). You need to use the new language idiomatically, which means learning it well. This is probably why Bjarne says most people don't put enough effort in for a useful comparison.

The type of comparison that starts with "I like Blub" and continues with "Well, I like Blub++" is completely useless. If it winds up selecting a language, all it really tells you is who's most persuasive in a given group and/or which language company has the largest advertising budget. If you analyze what a language can do, what tasks its suited for, and where its shortcomings are without resorting to unreasoned arguments or personal bias, then that can be useful indeed.

Title: Are Language Comparisons Meaningful?

Body:
Dr Bjarne Stroustrup in his book D&E says

Several reviewers asked me to compare C++ to other languages. This I have decided against doing. Thereby, I have reaffirmed a long-standing and strongly held view: "Language comparisons are rarely meaningful and even less often fair" . A good comparison of major programming languages requires more effort than most people are willing to spend, experience in a wide range of application areas, a rigid maintenance of a detached and impartial point of view, and a sense of fairness. I do not have the time, and as the designer of C++, my impartiality would never be fully credible.

-- The Design and Evolution of C++(Bjarne Stroustrup)

Do you people agree with his this statement "Language comparisons are rarely meaningful and even less often fair"?

Personally I think that comparing a language X with Y makes sense because it gives many more reasons to love/despise X/Y :-P

What do you people think?