问:
Do iterative methods reduce cyclomatic complexity and improve supportability?
Do iterative methods such as are commonly found in modern languages such as C#, JavaScript, and (hopefully) in Java 8 reduce cyclomatic complexity's impact on understandability and supportability of code?

For example in C# we might have the following code:

```<code>List<String> filteredList = new List<String>();

foreach (String s in originalList){
   if (matches(s)){
      filteredList.add(s);
   }
}
</code>```

This has a simple cyclomatic complexity of 2.

We could easily re-write this as:

```<code>List<String> filteredList = originalList.where(s => matches(s));
</code>```

Which has a simple cyclomatic complexity of 0.

Does this actually result in more supportable code?  Is there any actual research on this topic?

答: All you are doing is highlighting a flaw in cyclomatic complexity as a metric, the complexity of the code really hasn't changed. You have an explicit branch in the first example and need to understand there is an implied branch in the second. The second is clearer and easier to understand provided you understand the syntax, and since it uses less basic syntax that may be an issue.</p>


答:
My guess is that you just divided/moved the complexity. It decreased because you doesn't count the implementation of .where() in your CC.

The overall CC hasn't really moved, your own code's CC decreased, only because it's now moved to the framework's code.

I'd say it's more maintainable. When it's a feature of the language, use it. It's no a "ohh, I see, it's a clever trick" that you're using, only a simple inline reduce-like function.

ContentLicense: CC BY-SA 3.0

Title: Do iterative methods reduce cyclomatic complexity and improve supportability?

Body:
Do iterative methods such as are commonly found in modern languages such as C#, JavaScript, and (hopefully) in Java 8 reduce cyclomatic complexity's impact on understandability and supportability of code?

For example in C# we might have the following code:

```<code>List<String> filteredList = new List<String>();

foreach (String s in originalList){
   if (matches(s)){
      filteredList.add(s);
   }
}
</code>```

This has a simple cyclomatic complexity of 2.

We could easily re-write this as:

```<code>List<String> filteredList = originalList.where(s => matches(s));
</code>```

Which has a simple cyclomatic complexity of 0.

Does this actually result in more supportable code?  Is there any actual research on this topic?


答:
In order to answer the question objectively, we'd need some sort of metric for maintainability. Cyclomatic complexity itself isn't a measure of maintainability, but it is a component of some metrics that purport to measure maintainability. For example, the formula for the Maintainability Index is:

```<code>MI = 171 - 5.2 * ln(V) - 0.23 * (G) - 16.2 * ln(LOC)
</code>```

where G is the cyclomatic complexity of the code in question. Therefore, reducing the cyclomatic complexity of a piece of code does by definition improve the code's Maintainability Index and other metrics which similarly use cyclomatic complexity.

It's hard to say whether the kind of change you propose makes the program seem more maintainable to programmers; that probably depends on how familiar they are with (in your case) the where method.

Body:
In order to answer the question objectively, we'd need some sort of metric for maintainability. Cyclomatic complexity itself isn't a measure of maintainability, but it is a component of some metrics that purport to measure maintainability. For example, the formula for the Maintainability Index is:

MI = 171 - 5.2 * ln(V) - 0.23 * (G) - 16.2 * ln(LOC)

where G is the cyclomatic complexity of the code in question. Therefore, reducing the cyclomatic complexity of a piece of code does by definition improve the code's Maintainability Index and other metrics which similarly use cyclomatic complexity.

It's hard to say whether the kind of change you propose makes the program seem more maintainable to programmers; that probably depends on how familiar they are with (in your case) the where method.


问:
CMS updates into subversion -> review process
We manage a range of client sites built in Wordpress and Joomla and these require regular updates to the core CMS and extensions. We keep these sites in subversion and place updates in subversion. We try to use a single revision for this.

We face some difficulties in making this process efficient, over time we would like to automate it, so we can offer the process on a fixed price basis

The process is currently as follows

make copy of whole folder

svn status |grep '^!' |sed 's/^!\s*/svn delete "/g' |sed 's/$/"/g' |sh

svn update

svn status |grep '^?' |sed 's/^?\s*/svn add "/g' |sed 's/$/"/g' |sh

svn ci -m "Commit message"

svn remove -m"temporarily remove" http://subversion.repository.com/svn/automatem/projects/client/trunk/project/foldername

Steps 5-6 are usually repeated multiple times.

What I'm looking for help with

we are using subversion version 1.6 and 1.7, because there are no .svn folders in 1.7 in subdirectories, I wonder if the process is much easier on 1.7?

we've added step 3 because it reduces the number of repeats in steps 5-6. However this was just trial and error and I can't quite get my head around why this is

As I understand it, the issue in step 5-6 is that when the an extension is updated, it may delete a whole folder and then re-insert that folder with changed files. In subversion 1.6, this would remove the .svn folder, which causes a 405 Access denied error (the folder gets added, but already exists in svn). What I would need is something that inserts all .svn folders back into my working copy if the folder already exists in svn. Is there a way to accomplish this?

Any other improvements of course appreciated.

答: This looks like a good job for externals.  Joomla and Wordpress are both hosted on subversion, which makes externals a natural fit.  Basically, instead of making your own copy of a folder and trying to manage the changes, you tell it this folder should be pulled from a certain revision from a certain external repository.</p>


问:
What is the relationship between a framework like RoR and a database?
I'm a front end developer...I've never done ANY backend, although I did take a course in databases once. (I have a comp sci degree; I'm a competent programmer, I just haven't done any backend web stuff before.)

So I'm trying to figure out how the framework relates to the database. Presumably they're set up separately, and the framework receives requests from the website and sends them to the database, then receives the response and handles it appropriately to deliver the content correctly? It's basically a complex intermediary for all the web-app logic? Am I far off?

Need a good explanation of this.

答:
There are many possibilities to connect a web-app to a database (and a lot of different databases to choose from).

I think you should first consider the normal case (as e.g. most used in the RoR community):

a relational DB and a ORM (the object relational mapper - in RoR it is ActiveRecord based on the active record pattern).

a very high-level (and superficial) introduction:

the database is a separate entity and process.

the app defines models that describe both the tables in the relational database (RoR will create the necessary SQL commands) and the the way the data in the database can be accessed and modified from the web-app using objects and properties.

in your web-app-code you access the database only by interacting with those models. e.g. in RoR:

the users make requests to the web-app

the requests are handled in the controller.

the controller creates or retrieves records (e.g. by invoking find(<id>) on the class object) from the DB. these records appear as objects (or arrays of objects).

the controller modifies them, and

stores the result back to the DB (e.g. by invoking save() on the object).

the response e.g. shows the result to the user.


答:
Where as a website that doesn't change can just serve static pages, a web application like amazon has got a lot to do to present a page that represents a product: put simply, it can retrieve the product details based on an identifier passed in and build a web page that displays those details.

I would say a web framework relates to a database in the following way:

"A web framework is used to build/run a program that requests from a webserver run to build responses that can use data stored in database."

Title: What is the relationship between a framework like RoR and a database?

Body:
I'm a front end developer...I've never done ANY backend, although I did take a course in databases once. (I have a comp sci degree; I'm a competent programmer, I just haven't done any backend web stuff before.)

So I'm trying to figure out how the framework relates to the database. Presumably they're set up separately, and the framework receives requests from the website and sends them to the database, then receives the response and handles it appropriately to deliver the content correctly? It's basically a complex intermediary for all the web-app logic? Am I far off?

Need a good explanation of this.


答:
Subjectively, it depends on the developer audience, if they understand lambda expressions, then;

```<code>List<String> filteredList = originalList.where(s => matches(s));
</code>```

is quicker to understand, and perhaps slightly easier.  I would be more concerned about using s, and matches().  Neither is self-descriptive, something like;

```<code>List<String> filteredList =
    originalList.where(stringToBeTested => matchesNameTest(stringToBeTested));
</code>```

Or

```<code>List<String> filteredList =
        originalList.where(originalListString => matchesNameTest(originalListString));
</code>```

gives the developer more meaningful information and is easier to analyze, without having to dive into the matches() function to determine what match is being performed.

Maintainability is not only about the ability to comprehend the code, but mainly about the speed and accuracy with which one can comprehend the code.

Body:
Subjectively, it depends on the developer audience, if they understand lambda expressions, then;

List<String> filteredList = originalList.where(s => matches(s));

is quicker to understand, and perhaps slightly easier.  I would be more concerned about using s, and matches().  Neither is self-descriptive, something like;

List<String> filteredList =
    originalList.where(stringToBeTested => matchesNameTest(stringToBeTested));

Or

List<String> filteredList =
        originalList.where(originalListString => matchesNameTest(originalListString));

gives the developer more meaningful information and is easier to analyze, without having to dive into the matches() function to determine what match is being performed.

Maintainability is not only about the ability to comprehend the code, but mainly about the speed and accuracy with which one can comprehend the code.


问:
How to deal with WYSIWYG editors?
There are now lots of WYSIWYG editors, however whenever we use one on a CMS-based website we consistently have issues.

The biggest being users pasting content from Word or other online sources and all the various formatting rules being added in "behind the scenes".

How do you deal with these editors on a live production website?

I love Markdown, however its target market is most definitely the tech industry.

答:
I needed a form-based front end for users to create and update XML content. I did this by breaking the major XML sections into separate input or WYSIWYG textareas. Most of the in-browser editors seem to rely on the same basic contentEditable set of functions, so I just use the lightest-weight one that I've found so far--Whizzywing. I use PHP's strip_tags() on the input fields and I pass the rich text content through PHP's tidy tool with the output-xml option in effect (among others for removing spurious style attributes and normalizing the semantic phrases). I have also used the htmLawed library with equal success. Tidy has a word-2000 cleanup option that may be useful as well.

With well-formed XML as the output from this step, I then use an XSLT transform to finish the cleanup. This is the stage where you can apply business rules to your process... the fault of both editors and the various purifiers is that they assume direct reuse of the HTML content, whereas if you need to apply any kind of QA check or business rule compliance check on the content, these checks are best done by writing appropriate XSL templates that can reorder or retag the content to fit the rules. This is effectively the benefit you get from using Markdown-to-HTML transforms, but this process gives users the more appealing WYSIWYG front end plus Word-pasting as a benefit.

These steps go a long way toward cleaning up most things that can be pasted from Word into HTML while still maintaining a directed order for the eventually-saved result. It is very similar to the process used by the iFixit web site for rich text content authoring. They produce oManual XML format at the end of the save step; I'm producing a simple form of DITA, FWIW.

ContentLicense: CC BY-SA 2.5

Title: How to deal with WYSIWYG editors?


问:
Is there a reason that tests aren't written inline with the code that they test?
I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?

答:
For many of the same reasons that you try to avoid tight coupling between classes in your code, it's also a good idea to avoid unnecessary coupling between tests and code.

Creation: Tests and code may be written at different times, by different people.

Control: If tests are used to specify requirements, you'd certainly want them to be subject to different rules about who can change them and when than the actual code is.

Reusability: If you put the tests inline, you can't use them with another piece of code.

Imagine that you've got a chunk of code that does the job correctly, but leaves a lot to be desired in terms of performance, maintainability, whatever. You decide to replace that code with new and improved code. Using the same set of tests can help you verify that the new code produces the same results as the old code.

Selectability: Keeping the tests separate from the code makes it easier to choose which tests you want to run.

For example, you might have a small suite of tests that relate just to the code you're currently working on, and a larger suite that tests the entire project.


问:
WYSIWYG Editor - Inline Comments
I am working on a user driven cms site.  Think of it like stack overflow.  The users can write posts, and publish them to the web.  I am using a WSGI editor to generate the content.

One of the features I am implementing is the ability for users to comment on particular section of a user post. I am trying to think of a clean way to implement this feature.

My current plan is to customize the WYSIWYG editor to generate a unique id per
 and then store the comments separately, and when the page loads also read the comments and do some jquery magic. All users that are going to be generating content will be admin users, so I am not afraid of someone messing around with ids.

This is one approach I have found, but I was hoping to either get some feedback or alternative ways to accomplish what I need.  Another thing I am trying to figure out is how I can handle a user editing a post that has been commented on...

答:
This algorithm that I recommend depends on maintaining the data model for the operations in your database and using that model to generate the interfaces and the links in the reading mode of the document, rather than allowing direct editing of the main document. A link-based approach in the rendered (not editing) view allows someone to participate in the comment workflow without actually letting them edit the main document directly; you can just use textareas or input fields in the popover or new page-based form for these interactions. I've used this approach for department-wide reviews.

Clicking on a paragraph may not be an obvious behavior for new users. When you generate the id for a comment-worthy component (be it paragraph, list item, blockquote, or such), consider adding a superscripted link at the end with a clear label or icon that invites clicking for interaction. Then either pop over a window with your form, or open a new page (depending on accessibility preferences) to accept that input, keyed to that generated id. You'll have to index that stored comment by the document id and the corresponding component id.

For rendering the comments, when a component has a new comment, you can add a new "see comments"-style link following that original "comment here" link; again, this added link can either pop up a window with the dialog (since it could be one or more contributors) keyed to that component, or link to endnote-style comments displayed conventionally beneath the document. Extra credit for adding disposition controls within each component's group of comments that track how you have used or dismissed the suggestions!

How do you keep all this review interfacing separate from the clean document content itself? For HTML source, I'd keep just the id/name attribute on the components themselves and add the review links at display time based on walking the document tree and applying the links into the DOM before the rendition. I typically have an XML-based source so I use  an XSLT template to recognize these nodes and add the markup during the conversion into the HTML result tree. Either way, your original source remains free of comment/review markup except when it is in a view that you intend to allow commenting in. You can turn off this added step when the review is over or when commenting is closed.

Title: WYSIWYG Editor - Inline Comments


答:
Because it has been shown that cyclomatic complexity (CC) is very strongly correlated with code size, "so much so that CC can be said to have absolutely no explanatory power of its own." what you are really asking is whether "iterative methods such as are commonly found in modern languages such as C#, JavaScript, and (hopefully) in Java 8 reduce code size's impact on understandability and supportability of code."

At that point, one would hope that the answer would be obvious.  It has been known for decades that shorter code is generally easier to understand, maintain, and support.


问:
How to choose between lightweight or heavyweight framework for web application
In my current role as a software developer in a Java/Spring/Hibernate/JSF shop, I am sometimes asked to develop large-scale web apps with many interfacing systems and/or large databases as well as small-scale web apps with low traffic and/or simple databases.  To accommodate this variation, I would like to have 2 technology stacks to choose from, depending on the type of application I'm asked to develop. I think this would benefit us because I think our technology stack that I mentioned above is a bit over-engineered or cumbersome for small, simple CRUD applications.

If, for example, I have chosen Spring Framework for my large-scale apps and Play! Framework for my small-scale apps, how do I choose which one to use for a given application?  In other words, how can I tell if a proposed web application qualifies for a heavy framework like Spring or could stand to benefit more from a lightweight, agile framework like Play?

Can someone give me some rough checkpoints to help me decide which type of framework to use (heavy or light)?  If you use this two-framework approach, please tell me what criteria you use to decide which framework is the best fit for a given web application.

答:
Indeed a full scale Java/Spring/Hibernate/JSF implementation may be a bit too engineered for the requirements of many small scale systems, however I typically evaluate new application requirements on the following factors to help myself determine the appropriate architecture:

Anticipated User Load

What is the anticipated user load?

Are there potentially an enormous amount of users?

Are the users performing tasks that will utilize high amounts of resources?

Will the application need to scale horizontally with increased load?

Anticipated Future Scope

This one is hard to judge sometimes because the scope can sometimes be at the whim or will of a product manager or sales person.  If you anticipate that there is even the smallest possibility that a salesperson could try to brand it and sell it to anybody other than the original stakeholders then it is probably best to go with a more layered approach.

Distributed System Needs

Are there any anticipated needs for various differing consumers to achieve different information in different ways (Mobile app, ETL, SSO, public web services, etc...) then you always want to have a three tier distribution approach and have logical seperation of components and layers.  These types of architectural requirements will be better served by a more engineered approach.

Budget Constraints

What is the allocated budget for hosting the application in production?  Will it require expensive proprietary software licenses, multiple VPS's, high availability cloud computing?  Perhaps if you are only allowed a limited budget then CHEAP hosting technologies like PHP may make a lot more sense.

Knowledge Constraints

What is your team more efficient in implementing?  What are their skills and weaknesses.  Sure Play Framework may look cool for rapid application development, however if there is a significant learning curve there then perhaps you take less risk in the more cumbersome over-engineered approach that is well understood.

Time Constraints

How much time do you have to develop the application.  This also plays into Knowledge Constraints as time needed to learn a new technology can be an imposition on time.


问:
Developing on a production server
Today I got yelled at for developing an application on a production server. Quote, "developing on a production server is not acceptable - ever!"

Here is the situation.

I set up a development instance: http://example.com:3000

The production instance is: http://example.com

I complete all my development work on http://example.com:3000 and when the client is pleased with the changes, I move them over to http://example.com.

The application I am working with is an old Ruby on Rails application, and I have to say that initially, I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

Again, am I an idiot? Probably so, but I've been doing web development for a couple of years now, and I have never encountered a situation like this. Who is right and why?

答:
Another problem with developing on prod is that, sometimes, these things get missed in source control and a future release might undo your quick-fix change.

If you are in a publicly traded company in the US, you should not even have access to prod for regulatory reasons. In general, in no company should a developer have prod access (for the resons stated in all the answers as well as possible legal reasons), so your manager is also in the wrong for allowing you the rights to that server.

Title: Developing on a production server


答:
I think your concept of having unique IDs per paragraph, with the comments stored separately, is pretty solid. But, like you mention, you are stuck with the problems of users editing their posts.

If you have the revision history of the posts maybe the comments could stay with a particular revision.

You could use a diff tool or a Levenshtein distance calculation to help you decide what happens with a comment. You still have to deal with the questions: Should the comment still stay if a paragraph has been edited? Should the comment be deleted if the paragraph is deleted? etc. But having the work done by a diff tool for example may simplify things for you as it should be able to simply tell you if a line is added, deleted, or modified.

Keeping it simple, if you don't know what has happened to an edited text either delete the comments or convert them from a comment on a specific paragraph to a comment on the whole post (if this is possible).

Title: WYSIWYG Editor - Inline Comments

Body:
I am working on a user driven cms site.  Think of it like stack overflow.  The users can write posts, and publish them to the web.  I am using a WSGI editor to generate the content.

One of the features I am implementing is the ability for users to comment on particular section of a user post. I am trying to think of a clean way to implement this feature.

My current plan is to customize the WYSIWYG editor to generate a unique id per
 and then store the comments separately, and when the page loads also read the comments and do some jquery magic. All users that are going to be generating content will be admin users, so I am not afraid of someone messing around with ids.

This is one approach I have found, but I was hoping to either get some feedback or alternative ways to accomplish what I need.  Another thing I am trying to figure out is how I can handle a user editing a post that has been commented on...


问:
Using testing branches in Git
We have someone (let's call him Ted) that is responsible for testing new features and bug fixes.

We're using Git and GitHub. master should be/is always deployable and development is where we commit/merge new features or bug fixes, but only after they have been tested by Ted.

The project is in PHP.

I'd like the testing process to go like this:

A developer wants to work on a new feature (let's say the feature/bug #123 as Ted documented in the issue tracker), so he pulls origin/development to development on his local repository and creates a new branch (let's say issue-123) from there.

Once he's happy with his work, he commits and pushes his new branch to origin.

Ted connects to test.ourproject.com/choose-branch and sees a list of the branches on origin and chooses to switch on issue-123 (it should be doable through the webpage). He then goes on test.ourproject.com, tests the hell out of the web application (he's really pitiless) and after some back and forth with the developer, he's happy with the feature.

Ted tells the developer that he can merge issue-123 onto development on origin.

Rinse and repeat.

For the third step, I could hack something that does the job (showing and switching branches from a specific page), but I feel that what I've described is a very common pattern.

So my question is:
Is this a good / sustainable / maintainable workflow for branching? Can you back up your answer by citing some examples of other projects following this workflow?

答:
The branch workflow sounds a lot like gitflow http://jeffkreeftmeijer.com/2010/why-arent-you-using-git-flow and there are support tools around it.  It is highly recommended.

If there is only one tester, your testing workflow sounds fine, but if there are multiple people then development might  move between start and finish, and of course testing should ideally be fully performed after any merge.  This is where automated testing can really help or a slow (thorough) tester might never finish!

Another problem is that with many features and branches it becomes temping to mix and match features into a release (or to choose to evict after acceptance and merging) or perhaps if features are dependent on each other.  The problem is if you start getting temped to rewrite history (rebase/delete a commit or merge) on a PUBLISHED branch-meaning one which has been pushed to a multidev repo.  This is rewriting public history.  It can be done for good or evil and even if done for good can cause problems to the unwary, and best practice is to avoid it so the question will never come up.  However, some integration branch workflows make this very tempting, so if you have strong protection on such branches (eg gitolite per user branch restrictions) and people expect such activity so always rebase their code on such a branch, proceed--with caution!

I'd also like to recommend reading http://sethrobertson.github.com/GitBestPractices/ which discusses all of these matters and has many good references.

Title: Using testing branches in Git


问:
Finding subtree in a tree
I have a tree:

```<code>    a
   / \
  b   c
 / \
d   f
   / \
  g   h
</code>```

And the pattern:

```<code>    x
   / \
  y   z
 / \
q   p
</code>```

As output I would like to have:

```<code>x: a
y: b
z: c
q: d
p: f
</code>```

and

```<code>x: b
y: f
z: c
q: g
p: h
</code>```

Is there any algorithm I could look at?

答:
Flatten your pattern into a breadth-first array of tuples including the node name, depth, and index, like:

(a,0,0), (b,1,0), (c,1,1), (d,2,0)...

Traverse (or flatten) your input tree in breadth-first order, ideally using the same method.

The n-th item in your pattern array will match the n-th item in the input tree, assuming there is one. You can use the depth and index values of each tuple to skip ahead until something matches.

  There are really good breadth-first traversal code samples all over the place, it should be easy to find one in the language of your choice.

Title: Finding subtree in a tree


问:
Tineye.com search algorithm?
I was wondering how does tineye carry a search. Does it store all the images and then extracts exif data? Which in turn must be stored in a database and queried against. So probably it is using some sort of keyword/pattern matching algorithm... </p>

答:
The TinEye FAQ reads:

When you submit an image to be searched, TinEye creates a unique and
  compact digital signature or 'fingerprint' for it, then compares this
  fingerprint to every other image in our index to retrieve matches.
  TinEye can even find a partial fingerprint match. Those fingerprints
  use only the image itself, and not its name or surrounding text. Our
  fingerprinting technologies were developed by Idée Inc.

TinEye does not typically find similar images (i.e., a different image
  with the same subject matter); it finds exact matches including those
  that have been cropped, edited or resized.

Chasing this then to Idee and a google patent search for "idee image search" brings up a number of patents (mostly named "Methods and Systems for Content Processing").

While my digital signal processing background isn't there, these patents do appear to be similar to what TinEye implements... or if not specifically licensed by TinEye, do similar things with other algorithms that accomplish the same end (many of the results appear to be referencing things that TinEye does).  The patents are much larger than those I have glanced at before - some reaching over 100 pages.

Unfortunately, neither of the founders of Idée, Inc. come up in the patent search - which is often a valid approach to finding the patents they started with.

Title: Tineye.com search algorithm?


问:
Java Xml intraction in Android
I'm working on Android application development. There is a question that always comes to my mind that: How XML interacts with Java code?. I mean Button inside XML is a view, but Button inside Java is a class.

For populating and XML layout we use setContentView(R.layout.name). What I want to know is how this XML code interacts with Java, what technique is used and what code is behind this. If any know please tell me in brief.

答:
To understand the relationship between the two, I need to first clarify one thing.  You say that "Button inside XML is a view, but Button inside Java is a class" which is true but a bit narrow.  A Button in XML is not just a View but it's also a class.

View is a Java class.  Button is a subclass of View.  The layout XML in Android is just a simple way to arrange a number of View objects to form a UI.  Anything you do in a layout XML can be done in Java code and it can accomplish the exact same thing.  Android has these layout XMLs to simplify the process.

Consider the following example.  These two scenarios will create the exact same UI.

Create UI with layout XML:

main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black" >

    <LinearLayout android:id="@+id/left_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

MainActivity.java

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
</code>```

Create UI in Java code:

MainActivity.java

```<code>public static final int LEFT_CONTAINER = 0x0710001B;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout parent = new LinearLayout(this);
    parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    parent.setBackgroundColor(getResources().getColor(android.R.color.black));

    LinearLayout child = new LinearLayout(this);
    child.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    child.setId(LEFT_CONTAINER);
    parent.addView(child);

    setContentView(parent);
}
</code>```

Now this is a very simple layout so the required code for each method is relatively light.  If we scale this up to a UI with multiple containers and multiple controls, the Java code method starts to get really cluttered and prone to error.  You're also creating the possibility for multiple dependencies on your MainActivity class since it's holding the IDs of the layouts within it.

By using the layout XML, you confine the majority of your layout issues to one separate file and you reduce the amount of code that needs to be written to create your UI as the Android Activity parent class will handle all of that for you.  Additionally, you can reduce cross dependencies by having all of your layout and view IDs confined to your R class that Android generates for identifiers.

Title: Java Xml intraction in Android

Body:
To understand the relationship between the two, I need to first clarify one thing.  You say that "Button inside XML is a view, but Button inside Java is a class" which is true but a bit narrow.  A Button in XML is not just a View but it's also a class.

View is a Java class.  Button is a subclass of View.  The layout XML in Android is just a simple way to arrange a number of View objects to form a UI.  Anything you do in a layout XML can be done in Java code and it can accomplish the exact same thing.  Android has these layout XMLs to simplify the process.

Consider the following example.  These two scenarios will create the exact same UI.

Create UI with layout XML:

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black" >

    <LinearLayout android:id="@+id/left_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

Create UI in Java code:

MainActivity.java

public static final int LEFT_CONTAINER = 0x0710001B;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout parent = new LinearLayout(this);
    parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    parent.setBackgroundColor(getResources().getColor(android.R.color.black));

    LinearLayout child = new LinearLayout(this);
    child.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    child.setId(LEFT_CONTAINER);
    parent.addView(child);

    setContentView(parent);
}

Now this is a very simple layout so the required code for each method is relatively light.  If we scale this up to a UI with multiple containers and multiple controls, the Java code method starts to get really cluttered and prone to error.  You're also creating the possibility for multiple dependencies on your MainActivity class since it's holding the IDs of the layouts within it.

By using the layout XML, you confine the majority of your layout issues to one separate file and you reduce the amount of code that needs to be written to create your UI as the Android Activity parent class will handle all of that for you.  Additionally, you can reduce cross dependencies by having all of your layout and view IDs confined to your R class that Android generates for identifiers.


答:
If you're talking about the raw stat of Cyclomatic Complexity, sure.  You just nuked it from 2 to 0.  If you're going by numbers, pure gain, all the way.

From a practical (read: human) perspective though, I would argue you've actually increased the complexity by 2.  One point of that comes from the fact that now some other programmer must bring or get knowledge of fluent-syntax LINQ to understand this code.

Another point of increased difficulty comes from understanding Lambda Expressions; though a Lambda is fairly straightforward in this instance, there are some paradigm shifts that have to be made to fully appreciate them.

This case, using a.where(x => matches(x, arg)) isn't terrible, and in all honesty is a great way to get some coworker to see and work with LINQ and Lambda expressions for the first time (I actually presented a tutorial on LINQ/Lambdas to some former coworkers using this and other sets of code, to great effect.)  However, the usage of these does require some knowledge.

I recommend caution, because I've seen cases where the LINQ refactor is actually significantly worse to read than what that foreach loop becomes.


问:
Engineering interview candidate refuses to use whiteboard
Today I experienced a first in a technical interview. The candidate refused to use the whiteboard to solve an algorithm question, as I requested. There was no sort of disability at play or anything (outside of nervousness). He simply said that he is uncomfortable using a whiteboard for difficult questions.

Oddly enough, we were able to work through it with me standing over his shoulder looking at his notepad. He even communicated his thoughts effectively enough for me to help him over the inevitable bumps. After this I asked him how he felt about collaborative work (as collaboration here is heavy) and he said he loves it. I asked him if he likes to get together with other developers to hash over problems on the whiteboard to which he said yes.

Is this some sort of red flag or am I just reading too much into this? In our environment, collaboration is a must.

ADDITIONAL DETAIL:

The candidate was being evaluated for a lead development position, in which case he spends much of his time communicating with his developers and less time coding than an individual contributor.

答:
I wouldn't be too concerned about it.  You aren't hiring him to work on a whiteboard; you're hiring him to work at a keyboard.  The whiteboard is an in-interview technique to help demonstrate his competence.  If that doesn't work well for him, but he's able to demonstrate his competence in other ways, then that's an irrelevant implementation detail.

From what you've written, he seems to be good at communicating and working through problems, and you noted that he was able to accomplish the required work on a notepad.  This solves the same problem as the whiteboard does: it gives the candidate somewhere to work through the process more slowly than typing, and without a Backspace key, while the interviewer watches to get a feel for their thought process.  From what's written here, I don't see any good reason not to hire him based on this.


答:
There's a big difference between hashing out code on a whiteboard when brainstorming and hashing code out on a whiteboard when there's a guy who already knows the answer staring at you and waiting for you to make a mistake. Some people get really nervous in that environment. And even if you are not nervous, being in technical interviews all day takes it out of you.

Case in point, I was recently the interviewee and the interviewer asked me a whiteboard coding question that I not only knew the answer to cold, I had written a freakin' blog article on how to do it. I was so mentally worn out after two solid days of talking about programming languages and doing coding questions that I just blanked on it and it took me probably ten times longer than it should have to write the solution. Very embarrassing. I can easily see how someone nervous about an interview could blank on any question instantly.

I have been on the interviewer side and had candidates who told me ahead of time -- like, days ahead of time -- that they were uncomfortable with whiteboarding. They asked if there could be some other way to test their knowledge of basic algorithms. Given that warning, I'm fine with actually setting up a machine in the user's preferred development environment, giving my coding problems, and letting them hash it out for reals.

In short, I don't consider it a "red flag", but that said it is reasonable for the candidate to let you know in advance that they show off their skills best in some other way.

Title: Engineering interview candidate refuses to use whiteboard

Body:
Today I experienced a first in a technical interview. The candidate refused to use the whiteboard to solve an algorithm question, as I requested. There was no sort of disability at play or anything (outside of nervousness). He simply said that he is uncomfortable using a whiteboard for difficult questions.

Oddly enough, we were able to work through it with me standing over his shoulder looking at his notepad. He even communicated his thoughts effectively enough for me to help him over the inevitable bumps. After this I asked him how he felt about collaborative work (as collaboration here is heavy) and he said he loves it. I asked him if he likes to get together with other developers to hash over problems on the whiteboard to which he said yes.

Is this some sort of red flag or am I just reading too much into this? In our environment, collaboration is a must.

ADDITIONAL DETAIL:

The candidate was being evaluated for a lead development position, in which case he spends much of his time communicating with his developers and less time coding than an individual contributor.


问:
coding style for If condition
I came across below style of writing if statements in C#, on msdn code examples. Usually when I write if statements, the conditions I would write `(Customer != null)

I want to know if there is any difference/gain in writing statement like below:

```<code>Customer customer;
if (null != customer)
{
  // some code
}
</code>```

Or

```<code>if ("" != customer.Name)
{
  // some code
}
</code>```

答:
I'm not sure in C#, but in C++ it's legal to assign value inside a if statement.

Writing the if this way prevent you from bad surprises if one forgets one character: something like if ( customer.Age = 15).

When inversing rhs and lhs it's not possible to assign customer.Age to the value 15 which is const.

So, probably the code you're reading was written by a former C++ folk.

But as MS Visual has warning for assignment inside ifs, I tend to never to write them this way.

Title: coding style for If condition


答:
While I probably would have followed up with a question about what sort of problem he feels is whiteboardable, I can kind of see his point.  If you're close enough to write on a whiteboard, you're too close to see the entire thing without moving your head.  For certain kinds of algorithms that could be frustrating.  I prefer whiteboards for writing a line or two, then stepping back to think about it.  The higher the writing to thinking ratio, the more I prefer an editor or a piece of paper.  In fact, I've been known to do a bunch of quick typing in my editor, then transfer the list to a whiteboard for the thinking part.

What might be seen as an eccentricity I see as a high degree of self awareness.  I would rather hire someone who knows he is more efficient on paper and asserts it, than someone who has no idea.  Also keep in mind that not all disabilities are visible.  He could be blind in one eye, or have limited peripheral vision, and prefers not to tell people unless absolutely necessary.


答: This is legal in C# and is colloquially known as a Yoda Condition. Many people in the C/C++ world like this because it guards at compile time against replacing == with = by accident. However, it has fallen out of favor in C# due to the fact the compiler will flag it (the single =) as an error in that instance (so long as it's not a boolean eval).

Title: coding style for If condition

Body:
I came across below style of writing if statements in C#, on msdn code examples. Usually when I write if statements, the conditions I would write `(Customer != null)

I want to know if there is any difference/gain in writing statement like below:

```<code>Customer customer;
if (null != customer)
{
  // some code
}
</code>```

Or

```<code>if ("" != customer.Name)
{
  // some code
}
</code>```


问:
Haskell AND Lisp vs. Haskell OR Lisp
I currently code with C, C++, and Python. I'm wanting to pick up a functional programming language, and right now I'm leaning toward Haskell. I do NOT want to start a "Haskell vs Lisp" war here; what I want to know is this: if I learn Haskell primarily for exposure to functional programming, what benefits, if any, will I gain from later learning Lisp?

答: The main benefit I see from learning Lisp is learning how to integrate FP into a real-world oriented multiparadigm language, rather than only learning it in the context of an academic language that emphasizes purity.</p>

Title: Haskell AND Lisp vs. Haskell OR Lisp


问:
How are line/column position data dealt with in parser combinator libraries?
I'm building a parser using a parser combinator library.  I need to keep track of where AST nodes started and ended in the textual input -- line and column numbers.

How is this problem approached and/or what are strategies for dealing with it?

Clarification: I'm asking about how/when/where the line and column data is calculated.  Two possible alternatives are 1) as an extra piece of state ala monads and monad transformers, that is updated whenever a token (character) is consumed, and 2) preprocessing the token stream to add the line/column to each one.

Drawbacks:  1) would result in the same work being done multiple times if there's backtracking.  2) would increase memory usage a lot if the entire input stream were done up-front.

答: The component that has the information about the textual location is usually the lexer, not the parser. Typically, you might attach the location (line/column) to the token itself, so that the parser can access the source location information when dealing with input tokens.


答:
I have constructed parsers with Bison. Typically, position data is dealt with by Bison providing a location type, where when providing a token you also fill this type out with location information. Then you may access this location value when a rule is reduced.

IOW: you give it to Bison per-token and then it gives it back to you per-rule.

Title: How are line/column position data dealt with in parser combinator libraries?

Body:
I'm building a parser using a parser combinator library.  I need to keep track of where AST nodes started and ended in the textual input -- line and column numbers.

How is this problem approached and/or what are strategies for dealing with it?

Clarification: I'm asking about how/when/where the line and column data is calculated.  Two possible alternatives are 1) as an extra piece of state ala monads and monad transformers, that is updated whenever a token (character) is consumed, and 2) preprocessing the token stream to add the line/column to each one.

Drawbacks:  1) would result in the same work being done multiple times if there's backtracking.  2) would increase memory usage a lot if the entire input stream were done up-front.


答:
I wouldn't be concerned at all, if his notepad work was otherwise acceptable. </p>

<p>Writing on a whiteboard is physically different enough from handwriting on a horizontal surface or typing that it's hard for some people to do "fluently". Scribbling diagrams and scrawling notes, as normally happens during whiteboard collaboration, is also very different from writing clear code. </p>

Body:
I wouldn't be concerned at all, if his notepad work was otherwise acceptable.

Writing on a whiteboard is physically different enough from handwriting on a horizontal surface or typing that it's hard for some people to do "fluently". Scribbling diagrams and scrawling notes, as normally happens during whiteboard collaboration, is also very different from writing clear code.


问:
How to write user stories for a framework API
I need help understanding what user stories should look like for a web testing framework we are building for our organization's QA department. We are trying to run this project using Scrum.

The product will have 3 layers:

utility classes to make working with underlying web automation tool easier.

a page-object API layer which will allow our testers to write tests from the perspective of what services our web pages offer, instead from the perspective of the web automation tool.

a declarative layer, which will allow writing of tests in an English-type language--perhaps Cucumber-like scenarios. This layer will be mapped to the page-object API layer, so that if a test can't be performed declaratively, the test author can drop down into the page-object API layer.

The end-user of this framework is our QA group who will be writing tests either at declarative level,  or if they need to, the page-object API level.

My question is what should our user stories look like? Currently we have stories that cover what the web automation should be able to do (ie. find elements on the page, wait for elements to appear), but that can't be right. Firstly, we could deliver this kind of stuff already by giving the QA group the underlying automation tool. These stories are clearly not worth demonstrating in a sprint review.

Secondly, stories should indicate business value, which in this case is not in finding elements on a page, it's in:

having tests based on an up-to-date, popular and effective web
automation tool.

having readable tests

having the actual tests separated from the web automation tool which is driving them.

Fine, but how do I break the product up into more specific user-stories?

答:
I would suggest to slice vertically for stories, not horizontally:

As a QA group member, I can write a test using a page API that goes to a specific page, click on a button and verifies that I navigates to the right target page.

Then implement the page API layer and base layer necessary to support that, and no more. This is demonstrable and has business value: you can actually write a test and run it.

Then follow up with other vertical slices:

As a QA group member, I can write a test that goes to a specific page, fill in a text box, click on a button and verifies that I navigates to the right target page.

And incremental improvements (Cuke for instance)

As a QA group member, I can write a test using a cucumber like DSL that goes to a specific page, click on a button and verifies that I navigates to the right target page.

OwnerDisplayName: Aaron


答:
This is a dicey one. Scrum dictates cross-functional teams, which means that "user stories" for QA don't make any more sense than stories for developers. QA aren't users, they're part of the development process, and automated acceptance tests - assuming you're truly committed to having them - are best reflected as such.

When we first started doing this type of testing on my team, it was a spike. Then, it was rolled into the "testing" stage for every feature, and any framework-level development got charged to the individual tasks. This was intentional; we wanted to reflect to the management that the tests were no longer optional and that putting them off would just cause other features to take longer to develop.

When the tests start to get a little too rough around the edges, we parcel it off into tech debt and allocate a day or even a week to work on it.

I've had nothing but bad experiences with internal user stories. You're never quite sure when they're done because, as you're seeing for yourself, the acceptance criteria are wide open to interpretation.

If you're being forced to create user stories, what I would suggest is to create one story per service/action, for example:

As a tester, I would like to be able to automate a successful login via the web browser, so that I can write automated tests for logged-in features.

These stories will get repetitive, as stories often do when they're used inappropriately, but it's better than tests around finding elements on the page, which, as you say, is already offered by the framework. In this case, each story corresponds (roughly) to a Gherkin step or condition.

You could also parcel out all of the steps as tasks, and create a story for each entire page/service. Depends on how fast your team works. If you can model that entire page and all its services in one cycle then go for it. If you're not sure, stick to story-per-service or start a spike to improve your estimation.

Title: How to write user stories for a framework API

Body:
I need help understanding what user stories should look like for a web testing framework we are building for our organization's QA department. We are trying to run this project using Scrum.

The product will have 3 layers:

utility classes to make working with underlying web automation tool easier.

a page-object API layer which will allow our testers to write tests from the perspective of what services our web pages offer, instead from the perspective of the web automation tool.

a declarative layer, which will allow writing of tests in an English-type language--perhaps Cucumber-like scenarios. This layer will be mapped to the page-object API layer, so that if a test can't be performed declaratively, the test author can drop down into the page-object API layer.

The end-user of this framework is our QA group who will be writing tests either at declarative level,  or if they need to, the page-object API level.

My question is what should our user stories look like? Currently we have stories that cover what the web automation should be able to do (ie. find elements on the page, wait for elements to appear), but that can't be right. Firstly, we could deliver this kind of stuff already by giving the QA group the underlying automation tool. These stories are clearly not worth demonstrating in a sprint review.

Secondly, stories should indicate business value, which in this case is not in finding elements on a page, it's in:

having tests based on an up-to-date, popular and effective web
automation tool.

having readable tests

having the actual tests separated from the web automation tool which is driving them.

Fine, but how do I break the product up into more specific user-stories?


问:
What is the rationale behind Apache Jena's *everything is an interface if possible* design philosophy?
If you are familiar with the Java RDF and OWL engine Jena, then you have run across their philosophy that everything should be specified as an interface when possible.  This means that a Resource, Statement, RDFNode, Property, and even the RDF Model, etc., are, contrary to what you might first think, Interfaces instead of concrete classes.

This leads to the use of Factories quite often.  Since you can't instantiate a Property or Model, you must have something else do it for you --the Factory design pattern.

My question, then, is, what is the reasoning behind using this pattern as opposed to a traditional class hierarchy system? It is often perfectly viable to use either one.  For example, if I want a memory backed Model instead of a database-backed Model I could just instantiate those classes, I don't need ask a Factory to give me one.

As an aside, I'm in the process of writing a library for manipulating Pearltrees data, which is exported from their website in the form of an RDF/XML document.  As I write this library, I have many options for defining the relationships present in the Peartrees data.  What is nice about the Pearltrees data is that it has a very logical class system: A tree is made up of pearls, which can be either Page, Reference, Alias, or Root pearls.

My question comes from trying to figure out if I should adopt the Jena philosophy in my library which uses Jena, or if I should disregard it, pick my own design philosophy, and stick with it.

答:
What alex said is correct and are the best reasons I can think of for using interfaces wherever possible.  The dynamic proxy one is important because they cannot be used with classes, even abstract ones!

I am not familiar with Jena in particular, but a strong preference for interfaces is quite common in OOP.

The only danger to be careful of is the over-use of interfaces.  I can tell the programming-to-the-interface best practice has been abused when I see tons of interfaces with only a single implementation named after the interface and the word "Impl".

```<code>public interface WidgetManager {
    ...
}

public class WidgetManagerImpl implements WidgetManager {
    ..
}
</code>```

Could have just made WidgetManager a class and be done with it.  Instead, we've doubled the number of Java types needed and added an extra hoop to jump through when debugging.

Body:
What alex said is correct and are the best reasons I can think of for using interfaces wherever possible.  The dynamic proxy one is important because they cannot be used with classes, even abstract ones!

I am not familiar with Jena in particular, but a strong preference for interfaces is quite common in OOP.

The only danger to be careful of is the over-use of interfaces.  I can tell the programming-to-the-interface best practice has been abused when I see tons of interfaces with only a single implementation named after the interface and the word "Impl".

public interface WidgetManager {
    ...
}

public class WidgetManagerImpl implements WidgetManager {
    ..
}

Could have just made WidgetManager a class and be done with it.  Instead, we've doubled the number of Java types needed and added an extra hoop to jump through when debugging.


答:
AND please.

Haskell teaches you the purest of FP, as far as I'm aware at least, just like Smalltalk teaches the purest of OO. (I mention this not to suggest that OO and FP can't marry, but because both these languages are "gem" languages - a core idea taken to extremes.)

Lisp is really a family of languages, so I'll talk about Common Lisp because that's the particular member of the family I use.

Lisp will still have lots to teach you:

It's multiparadigm, so as dsimcha points out it'll show you how to integrate FP with other paradigms.

Lisp will teach you that "code-is-data, data-is-code", for example through its macros.

CLOS is a very interesting brand of OO, with multiple inheritance that works, and generic functions.

Title: Haskell AND Lisp vs. Haskell OR Lisp

Body: I currently code with C, C++, and Python. I'm wanting to pick up a functional programming language, and right now I'm leaning toward Haskell. I do NOT want to start a "Haskell vs Lisp" war here; what I want to know is this: if I learn Haskell primarily for exposure to functional programming, what benefits, if any, will I gain from later learning Lisp?


问:
Naming guard clauses that throw exceptions
I have a function evaluate() that parses a String for some variables and replaces them with their corresponding value:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    if (result.matches(".*\\$\\{.+\\}.*")) {    //<--check if a variable wasn't replaced
        throw new MissingValueException();
    }
    return result;
}
</code>```

Since the evaluate() function now does 2 things, it first replaces the variables with the values AND check for any variables that weren't replaced, I thought about refactoring it to:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    checkForMissingValues(result);
}

private void checkForMissingValues(String result) {
    if (result.matches(".*\\$\\{.+\\}.*")) {
        throw new MissingValueException();
    }
}
</code>```

Now is this a good name for the function checkForMissingValues? I mean it does check for missing values, but it also throws an exception.

I thought about renaming it to throwExceptionIfMissingValueWasFound(), but this name tells HOW the function does it more than WHAT the function is doing.

Is there a standard for naming such functions that check for a condition then throw an exception?

答:
Your routine name seems perfectly fine to me. What's so bad about "check"?

I tend to break it up, though. So I have a routine that does the check/throw, plus functions that do the actual tests. You'd wind up with something like:

```<code>check(!hasMissingValues(result));
</code>```

This makes it more than just a naming convention. You can call it "validate" or "enforce" or whatever, but the key it that check has a defined behavior.

(This of course assumes that the kinds of conditions you're checking don't need a bunch of custom exception info, but that is often the case.)

Body:
Your routine name seems perfectly fine to me. What's so bad about "check"?

I tend to break it up, though. So I have a routine that does the check/throw, plus functions that do the actual tests. You'd wind up with something like:

check(!hasMissingValues(result));

This makes it more than just a naming convention. You can call it "validate" or "enforce" or whatever, but the key it that check has a defined behavior.

(This of course assumes that the kinds of conditions you're checking don't need a bunch of custom exception info, but that is often the case.)


问:
C++ Typecasting VS performance
Let's say we're designing a video game. We have some sprites on the map and we want to call some method of the particular sprite at some particular position.

We are using one broadly-known C++ framework. It has an GraphicsItem class, and ALL our sprites are derived from it. Now, framework has a method to get a pointer of the GraphicsItem at any position on the map.

We've got two options now:

Cast from GraphicsItem* to our Sprite* and call Sprite's method. (We know for sure that all the graphics items on the map are instances of Sprite)

Make some crazy things like Store pointers to Sprite in some container, iterate through them, compare address vales and get straight Sprite* without casting.

The question is: what is the best practice in this case? I was always told to avoid typecasting because it means you've got design issues. But how can I change design to avoid typecasting here? And extra iteration over a container with a comparison is just... crazy...

答:
If you know that everything in the scene is an instance of Sprite, then there should be no problem with typecasting. You can enable RTTI and use dynamic_cast<Sprite *> to be extra certain.

If there may be other GraphicsItem elements that are not instances of Sprite, then you could keep a set (perhaps QSet<GraphicsItem *>) which holds pointers to instances of Sprite that should appear in the scene. When you get a pointer from the scene, check to make sure it is in the set of sprites. This has the disadvantage of requiring that you maintain the set alongside maintenance of the scene itself.

It certainly would not be necessary to create a mapping container that maps a GraphicsItem * to a Sprite *.

Title: C++ Typecasting VS performance


问:
Re-gaining confidence of senior programmer
My boss found out I'm not as smart as he thought.

An example from my experience:

I'm a junior programmer, and I work in a team of two, my boss (senior programmer) and myself.

I was tasked with developing an internal web-application for the company we work at. I wrote the back-end to the front-end (the database design was in already place and the server technology had been chosen). He would periodically check on my progress by observing the web-application in action and was happy with out it was coming along. When I finished the web-app he was pleased with how well the end-product turned out.

A few days ago he became interested in the code so I told him what technologies I used (for the front-end), and this is where it went south. For the front-end of the web-app I used a Javascript framework (Backbone.js). When asked why I would do such a thing. My response was because that I felt that the framework fit into this app quite well, and would help me structure the code better than if I wrote it from scratch...."Well, that's dis-heartening" was his response.

So given this example my question is:

If your a senior programmer and have lost confidence in the ability of your junior programmer, what would you like to see from your junior to gain the confidence back?

EDIT: Thank you everyone for the great answers and supportive feedback!

答:
If he liked the product you built, but is stuck up on your use of Backbone, you both need to have a conversation about the desired tech stack.

As developers, we ought to use tools that are readily available, and consequently, smoothly move our flow of work. If he expected you to build the front-end from scratch, he should have been explicit and had good reason.

The fact that he initially enjoyed the product is proof enough that you did well and are "smart" enough.

tl;dr You did well. Talk to your senior and see what he expects from you.


答:
First of all, I think this needs to be seen as an opportunity, not a failure.  There's obviously a mismatch in expectations and it isn't clear where that comes from, what needs to happen to get everything back on track and the like.

Secondly, if you take this as a current failure or that you aren't as smart as you think that sets up power relationships you don't want.  So if you made decisions you believe are defensible you need to be willing to defend them up to a point.

While I agree with duggieawesome that you want to have a conversation, that's not enough.  You have to be prepared to go in, discuss your design ideas, explain why you did what you did, and defend the reasoning.  You  also need to accept that there isn't only one right answer and that the senior programmer may have valid reasons for preferring a different design and so you want to go in being willing to listen to those reasons without conceding that your decisions were bad based on what you knew (unless you decide that you should have known better, and then that's another matter).

Keep in mind that design is usually a question of tradeoffs.  You want to be willing to discuss what the tradeoffs are, and see what you both can do to ensure you can discuss design tradeoffs in the future.  Maybe you two are just expecting you are more on the same page there than you are?  Maybe your boss is an idiot (it might happen sometimes)?  Maybe you really did make a decision that was wrong given what you knew about the requirements?  Go in with an open mind and with confidence however, and be willing to really talk about this.

Edit:  I want to add something about being smart.  The smartest people I know are people who figure they have something to learn from everyone.  People who are closed off and believe there is only one right way don't end up making imaginatively good decisions in areas like design and they can't connect things together the way that people who are willing to learn from everyone can.  Going in and being willing to share and even bounce ideas back and forth is a sign of both being smart and confident.  Differences in design do not necessarily become matters of one being better than the other.  Assuming competent designers, different designs will be differently optimized.

Title: Re-gaining confidence of senior programmer

Body:
My boss found out I'm not as smart as he thought.

An example from my experience:

I'm a junior programmer, and I work in a team of two, my boss (senior programmer) and myself.

I was tasked with developing an internal web-application for the company we work at. I wrote the back-end to the front-end (the database design was in already place and the server technology had been chosen). He would periodically check on my progress by observing the web-application in action and was happy with out it was coming along. When I finished the web-app he was pleased with how well the end-product turned out.

A few days ago he became interested in the code so I told him what technologies I used (for the front-end), and this is where it went south. For the front-end of the web-app I used a Javascript framework (Backbone.js). When asked why I would do such a thing. My response was because that I felt that the framework fit into this app quite well, and would help me structure the code better than if I wrote it from scratch...."Well, that's dis-heartening" was his response.

So given this example my question is:

If your a senior programmer and have lost confidence in the ability of your junior programmer, what would you like to see from your junior to gain the confidence back?

EDIT: Thank you everyone for the great answers and supportive feedback!


答: Learning Lisp later will allow you to customize Emacs which arguably is the most advanced text editor available.   You can't do that in Haskell.</p>

Title: Haskell AND Lisp vs. Haskell OR Lisp


问:
What is the C++ convention, if any, for naming to differentiate between structure types and other types?
In general, should I use some sort of convention for structure names which is distinct from other type name? I was thinking about this when my professor started talking about structures.

I had the following discussion with myself, and since I do not want to come to any unreliable conclusions. How would you answer the question(s) and which answer(s) are untrustworthy?

Q: Should I distinguish structure names and type names to make the code more clear?

A: A structure is a type, so there doesn't need to be a distinction.

RE: Q: So there is never a case when someone uses typedef int SOMETYPE to rename a built-in type to make the code more flexible?

RE: A: There is no practical reason to rename built-in types. Actually, defining int types as SOMETYPE makes the code less readable because someone reading the code will not know the built-in type used for that type.

Honestly I do not trust either answer. Looking at some of the base structure in a new Win32Project using Visual Studio, I see things like typedef short HFILE; which, I guess, makes it more clear to the programmer what the variable is used for. Perhaps that is too subjective however.

As an aside, how does one usually determine what is going on when they come across variable declarations which use types you have never seen before. Do you just rely on the IDE to take you to or display the declaration?

答:
In C++ structs and classes are equivalent, except that the default visibility for struct members is public, while for classes it is private.  The following are equivalent:

```<code>struct X { private: int i; }
</code>```

and

```<code>class X { int i; }
</code>```

There is no reason to give structs a special prefix.

Also, just because something is in the Win32 API doesn't make it a good idea

Perhaps typedef short HFILE was useful for a C API, in case they later wanted to change to typedef int HFILE.  It's a poor practice for C++, where you could write:

```<code>struct HFILE { short s; }
</code>```

This would allow passing HFILEs around by value as efficiently as shorts, while preventing unwanted conversion between an HFILE and numeric types.

Body:
In C++ structs and classes are equivalent, except that the default visibility for struct members is public, while for classes it is private.  The following are equivalent:

struct X { private: int i; }

and

class X { int i; }

There is no reason to give structs a special prefix.

Also, just because something is in the Win32 API doesn't make it a good idea

Perhaps typedef short HFILE was useful for a C API, in case they later wanted to change to typedef int HFILE.  It's a poor practice for C++, where you could write:

struct HFILE { short s; }

This would allow passing HFILEs around by value as efficiently as shorts, while preventing unwanted conversion between an HFILE and numeric types.


答:
He doesn't seem very "senior" to me to make a snap judgement call like that. I always tend to use a proper framework instead of the "Reinvent the square wheel" anti-pattern. If he was truly senior he would understand and know the value of a good framework. At best I would expect him to question Backbone.js choice over another MVC JavaScript framework and much earlier in the process. He failed in properly mentoring and checking up on you as a junior and help you along the proper development path (in his mind.)

It sounds like you made the right choice in developing the project given the lack of direction on his part (assumption) and are working towards being a more competent developer. I would think there might be value in explaining to him your choice of framework, why you felt a framework was appropriate, and point out that the project was done and to his satisfaction in part because of using well documented and supported framework. If you can't make progress perhaps there is no value in appearing better in his eyes. Only you can answer that.


答:
Majority of the answers and comments have the right idea in that you and the senior would need to have some sort of discussion and that it may be important for you to step up and defend your decisions, even if your senior does not agree with your choices.

To answer your question on what i would like to see as a senior:

I would like to see if my junior developers can stand up and defend his decisions, even if faint disappointment. If i were happy with the product but not with the implementation then i would expect the juniors to point out that i should have then been more specific in my specs when giving them the product. I would like them to be able to stand their ground but also to admit they may not have made the right choice should that be the case.

PS:
I must mention that i am a senior who loves to be proven wrong on a professional level as that grants me the opportunity to learn something new. And i like to be aware of how others in my team do things so that there are no / less surprises at the end of a Sprint / task.


问:
Encountering the same issue in an application
I've often come across the situation when the same mistake is made in many places in an application. For example, in a web application when the user creates an item and clicks the Add button to save it. If they click the button several times, multiple items are added instead of one because UI wasn't blocked and backend check wasn't performed properly.

How to create bug tickets in such cases?  Here are the solutions I could think of:

create one single bug ticket and list where the situation occurs

for every case found create a separate ticket

when finding the bug tell the development to pay attention, wait till they are finished and test again

答:
Talk to the development team (or even better your development team mates), how they prefer it.

The bug(s) are in the end work items for them, so their opinion is important.

Technically both options (and the third, having one 'super bug' with all the occurences as 'bug minions') are pretty much the same. The important part is here to make clear

what is the bug

where & when does it occur? On one page, on all pages, on many pages?

The rest is more psychology than anything else. I have seen a review that on reviewing a document made a review comment about a wrong formatting of headers separately for every single header in a 100+ pages document. He didn't made friends with that.

But if the bug has get fixed seperately on lots of pages and that takes maybe 3 hours per occurence a separate bug might be considered a nice thing, because it allows to check of progress in a reasonable fashion.

So to wrap it up: Talk to the team.


答:
I'm with the general opinion here that you haven't done anything wrong. As the senior developer, he should have taken an interest in how you were developing the application as well as the results. To come in after a project is completed and say he doesn't like how it was done isn't very professional on his part.

But, to answer your main question: how do you gain back a senior's opinion of you after it may have been lost? First of all, ask how they feel you should have done it. Ask questions if you don't understand and take notes. Show that you want to learn.

Second, on your next task, if there is something that has been left out of the description, come up with your ideas then run them by the senior dev. Don't flat out ask how to do it, b/c this won't help their opinion of you. But, if you come up with your own ideas and your own solutions, then ask them if you're on the right track, it will show them that you are trying and that you do have the skills to get the job done. This can be as simple as a quick email saying "Hey, I am planning on using x when doing y. Any thoughts?"

Third, when they pop their head in to see how you're doing, don't let them leave without looking at your code.

Basically, open the lines of communication. Your senior developer doesn't seem to be the type to be on you or your code, so you need to step up and be the person to communicate. It is better for everyone involved to find out something isn't exactly originally thought sooner rather than later.


问:
How to represent calculated deadline is reasonable?
As a Lead Programmer my responsibilities include calculating the deadlines of the projects.

To do this I have discussion with related team players and calculate a deadline estimation. Sometimes, I got a scared voice from CTO saying that the estimated deadline is too much. Then I have to shorten the deadline. With a shorter deadline, programmers have to work with extra pressure.

How can I represent (points) to the CTO that the calculated deadline is reasonable?

答:
One time-proven way is the scientific method, one could even say a data driven method :)

Ask a Question (When are we done?)

Do Background Research (What needs to be done? Divide et impera).

Construct a Hypothesis (Calculate the time of completion, deadline).

Test Your Hypothesis by Doing an Experiment. (Do multiple sprints, so you get real data from past sprints and estimations. The truth is in the data).

Analyze Your Data and Draw a Conclusion. (How accurate were we? Make adjustments. Learn. Repeat. Iterate.)

Communicate Your Results. (Tell your client/boss/CTO)

Multiple iterations is the key, so you get the real data to build on!

Source: Steps of the Scientific Method


答:
An implicit cast to first base type and the reverse static cast to derived type when you are certain it is that type are exactly zero operations at runtime. You can't beat that.

An implicit cast to non-first base type and the reverse static cast to derived type which has the base as non-first is a simple increment/decrement with a null pointer check. It has a cost, but it's trivial and you won't beat it with any lookup.

A dynamic cast reads the virtual method table pointer from the object, compares it to the one for the target class and if you are casting to what is still base of the actual type, follows some chain of pointers to check it. A bit higher cost, but it's still unlikely you could beat it with any kind of lookup.

So, by all means cast. Use dynamic cast if you need to check the type (the base type has to have at least one virtual member for it to work, but it's certainly the case here).

Yes, if you need to type-cast, it indeed usually means you have design issues. But in this case it is not your design issues. If the library provided a means to specify your own base class derived from the interface the library needs and returned that to you (via templating), you could do with virtual methods, possibly utilizing visitor patter from there. Alas it does not, so you have to cast. If you want, you could wrap the canvas in your own class that will do the casting and will also wrap the insertion to ensure that all items are indeed sprites.

Title: C++ Typecasting VS performance

Body:
Let's say we're designing a video game. We have some sprites on the map and we want to call some method of the particular sprite at some particular position.

We are using one broadly-known C++ framework. It has an GraphicsItem class, and ALL our sprites are derived from it. Now, framework has a method to get a pointer of the GraphicsItem at any position on the map.

We've got two options now:

Cast from GraphicsItem* to our Sprite* and call Sprite's method. (We know for sure that all the graphics items on the map are instances of Sprite)

Make some crazy things like Store pointers to Sprite in some container, iterate through them, compare address vales and get straight Sprite* without casting.

The question is: what is the best practice in this case? I was always told to avoid typecasting because it means you've got design issues. But how can I change design to avoid typecasting here? And extra iteration over a container with a comparison is just... crazy...


答:
One thing you need to find out right off the bat is whether he's disheartened because you couldn't give a comprehensive defence of your choice of framework, or if it's because you used a framework.

In the former case, it's important that you learn how to evaluate and select third party code for inclusion in a project, and that you know how to articulate that decision to your superiors and be prepared to stand by it with justification.  This is a tricky skill to learn, but it comes with experience.  It's also a good skill to learn because as soon as you include a third party library into a project you introduce a component that may not be fully understood by the other developers, that they don't have full control over, and may contain bugs, security holes and other things that they need to be aware of.

If he's disappointed because you didn't write it from scratch then that's a different issue entirely.  It may be that he has good reason to discourage the use of frameworks (such as the ones I described above), or maybe there's a company policy against them or limiting the choice of frameworks you can make.  Either way he should have communicated that to you and the fact that he didn't indicates a failure on his part.  On the other hand he may just have a case of framework prejudice, because in spite of the issues that frameworks can lead to, they also have major benefits as I'm sure you know.  He may just think you should make everything yourself, even if that means redoing work that's already been done and made publicly available due to "Not Invented Here syndrome".

That he didn't explain why he's disappointed in you for using a framework is certainly a failure on his part to communicate effectively.  He's left you wondering what you've done wrong, when the answer could well be "nothing".  He's also caused you to question yourself, and that's bound to make you less inclined to use your own initiative in the future.  If there's one trait a good programmer can't afford to have, it's a lack of initiative.  And while I'm sure it's unintentional, his attitude is damaging morale as he's suddenly withdrawn praise for a job well done over one small detail of how you accomplished the task.

Just because he's the senior programmer doesn't make him infallible.


答:
Your follow up comment that said the boss is upset he has to learn something new....

Unless there is more to it that you haven't mentioned, I'd be annoyed at HIM.

Learning new technologies is a great part of our job and every team should embrace learning and self improvement.

BUT, management have other things to worry about. They have deadlines to meet, they have limited or no training budgets.

From a man-management point of view, it might be someone else working on phase 2 of your project instead of you. You boss might have someone else ear marked for doing that work, and he knows that person now has a learning curve for something new.

And now a BUT on the previous BUT....... this is your bosses fault. If you are new and junior, he should have provided at least some guidance. To a lesser extent, you could have asked for guidance on the tech to use as well.


答:
If you're a senior programmer and have lost confidence in the ability of
  your junior programmer, what would you like to see from your junior to
  gain the confidence back?

Given that you've said that he didn't want to learn how to use the framework you've used, I think the question should be: "If you're a senior programmer and you've lost the ability to learn from your junior programmer, what should you do to sort yourself out?"

As a professional developer you do not stop learning. Ever. If you do, you are going to stagnate. And that might be fine in some areas. Banking has a lot of legacy systems in operation that need maintained so knowledge of old systems that move very slowly are fine. A friend of mine was editing COBOL for a bank to discover that the source code he was fixing hadn't been touched in about 30 years (and the original author was our COBOL lecturer at university)... That said, he still has to learn new stuff as old systems have to be integrated into new systems.

Back to your senior developer. You said "he was upset about having to learn something new", and in my opinion that is a rings some pretty loud alarm bells.

I'm always learning. While I'd really like my employer to pick up my education bill each year it is rare that they spend anything close to what I feel I actually need, yet I know that I must remain employable so I spend somewhere in the region of £2000 GBP (roughly $3000 USD) on my own education every year.

If your senior is not learning new things then they will start making poor decisions (maybe they already are) and the quality of the code you are dealing with will go downwards because they are stuck in a rut and don't feel the need to get out of that rut.

One of the best developers I ever worked with was a junior developer who knew all sorts of stuff I'd never had a chance to look at. He brought so much to the table I was often overwhelmed. But I appreciated his efforts and I was never "dis-heartened" by any of it. I was pleased that he took the time to appreciate all the possibilities and present them to the team. He now leads a team and he keeps telling me about developers that bring stuff to the table and what he's learning from them.

Your senior developer needs to learn things. They need to learn not to use emotive words (like "dis-heartening") to hide their own inadequacies, because that will knock others' confidence. They need to learn new frameworks (even if they can't learn the whole thing, learn what it does and how it solves a problem, and if they need it in the future then they can invest the time in learning more deeply). And they need to learn that they are in a job where they will have to keep learning all the time.


问:
How to synchronize client and server model objects?
We have a client-server application with a thick client (GWT).

There are client-side MVP presenters (MVC controllers) which hold references to some objects viewed in the GUI. Some user actions cause these objects to be updated on the server. After that we can send updated objects back to the client and reassign them to the presenter.

The problem is that there are usually a few references to an object on the client (Lists, HashMaps, etc.) and it is hard to update all of them.

Another approach is not to update the references but update the object itself, e.g. copy all the properties from the server object to the client one. But if an object is complex it is not easy too.

Which approach is better? Or maybe I miss something?

答:
This problem is almost identical to the synchronization one maintain between its code and the database.

Usually, backend code do the same workflow:

Request database

Create (hydrate) object from raw data

Manipulate data

If needed, update the database.

On the next request (in the case of a web app), you totally invalidate the hydrated objects you have, an begin from point 1. again, as you recognize the database to be the "upstream" source of the data.

From there, I'd say you have 2 paradigms:

Client - server like Server - database

Client to server sync is pretty much the same, you need to setup some cycle, where you consider that your data are still "fresh", then upon the next "action" of your user, query again the server (as you would do with a database), and create your client objects from there.

Push from server to client

Another solution is to have the server "push" the new object states to the client, as soon as it know they have been updated. Such paradigm is use by new frameworks like Meteor: servers listen to the database, wich emit an event upon every update/insert/etc. Servers then update their internals objects, and transmit the event to clients, which do the same (I'm simplifying for the sake of the answer).

Conclusion

In any case, there's no universal solution that you need to add as a library to your project. Caching is hard, like real hard, and you'll need to integrate the server - client constraints to your  code, and handle such cache yourself.


问:
Novel polymorphism - any reasons for this code?
As part of my work on a legacy C# application I've come across a novel (to me) use of an interface & concrete implementations.  I can't think of any reason why you'd do the following, but I'm pretty thick, so maybe someone else can?

```<code>public interface IContract
{
    ContractImplementation1 Contract { get; }
    bool IsCollection { get; }
    bool Touched { get; set; }
}

public class ContractImplementation1 : IContract
{
    public ContractImplementation1(string propertyOne, string propertyTwo, string propertyThree, string propertyFour)
    {
        PropertyOne = propertyOne;
        PropertyTwo = propertyTwo;
        PropertyThree = propertyThree;
        PropertyFour = propertyFour;
    }

    public ContractImplementation1 Contract { get { return this; } }
    public bool IsCollection { get { return false; } }
    public bool Touched { get; set; }

    public string PropertyOne { get; private set; }
    public string PropertyTwo { get; private set; }
    public string PropertyThree { get; private set; }
    public string PropertyFour { get; private set; }

    public override string ToString()
    {
        if (string.IsNullOrEmpty(PropertyFour))
            return string.Format("{0} => {1}: {2}", PropertyOne, PropertyTwo, PropertyThree);
        else
            return string.Format("{0} => {1}: {2} {3}", PropertyOne, PropertyTwo, PropertyThree, PropertyFour);
    }

}

public class ContractImplementation2 : IContract
{
    public ContractImplementation1 Contract { get { return null; } }
    public bool IsCollection { get { return true; } }
    public bool Touched { get; set; }

    public List<ContractImplementation1> Contracts = new List<ContractImplementation1>();
}
</code>```

I can't get my head around the super-type having a property that is a sub-type of itself.

Following Cosmin's answer: I can't get my head around why you'd have the sub-type as a property given that the property returns itself on the implementation (rather than a 'parent' of the same type i.e. a different instantiation of the super-type).

答:
I can't get my head around the super-type having a property that is a sub-type of itself.

The code you posted, with PropertyOne, PropertyTwo ... PropertyFour is probably just an example, so I'll assume the liberty to provide my own example of a case where the super-type having properties that are sub-types of itself makes obvious sense:

Let's say you've got a class Human with subclass Male and subclass Female. If you'd add the properties Mother and Father to Human, it makes sense for them to be of the sub-type Female and Male.

Given this example, the generic answer is: if the super-type and the sub-type have enough in common, why not? I can imagine this sort of situation arising quite often in tree-like structures.


答:
Making estimations becomes much easier when the work is divided into smaller tasks. And the smaller the tasks are the easier it is to estimate them. This way the estimation become more accurate.

This also helps to clearly see how much time will be spent on each task. So when the management is complaining about the deadlines, you can show them what exactly the time is spent on.

If the deadline isn't acceptable, some of the initial functionality should be reduced. Reasonable managers will go for a high quality product with fewer features than a pile of not-properly-working functionality.

Another trick is to "cheat" giving a little bigger estimations than necessary. But I think this is an extreme.

Title: How to represent calculated deadline is reasonable?

Body:
As a Lead Programmer my responsibilities include calculating the deadlines of the projects.

To do this I have discussion with related team players and calculate a deadline estimation. Sometimes, I got a scared voice from CTO saying that the estimated deadline is too much. Then I have to shorten the deadline. With a shorter deadline, programmers have to work with extra pressure.

How can I represent (points) to the CTO that the calculated deadline is reasonable?


答:
I've always maintained that any software project has four variables:

StartDate

Duration

Effort

Staffing

You can control any three of them, but the fourth is a function of the other three.

If you set StartDate=W, Duration=X days, and Effort=Y person-hours, you're going to need Z people.

If you set StartDate=W, Effort=Y person-hours, and Staffing=Z people, it's going to take X days.

etc.