问:
Are multi-line comments a critical facility in a modern language?
I'm trying to convince the designers of a language that multi-line comments with an arbitrary start and end are important, and should be included.  Currently there is only a "comment-to-end-of-line" primitive.

Their line of argumentation reminds me of what some say about why you should use spaces instead of tabs.  Basically that editor features can pick up the slack and remove the requirement for a different construct.  (So if you wanted to comment out more than one line, you'd select what you wanted and run a macro of some kind...to add or remove a to-end-of-line comment to each line.  I just read that this feature exists in Visual Studio, despite C/C++ offering a multiline comment.)

Other suggestions about removing blocks of code from execution wind up being things like "cut the code out, try it, and use the redo queue".  I think this is not a very easy way to keep track of "invisible" information you might want back, and redo queues are quick to lose information the moment you hit even a stray key on accident.  So this does not sway me.

I can live with the space vs. tab thing and putting that on the editor, and it's now pervasive.  But to me this is different, and I'm dissatisfied with these answers.  For me, being able to comment out code with just a start and end marker like /* and */ is extremely useful.  Passing the buck to editor magic doesn't let you position your starts and ends arbitrarily (how would you comment out the middle of a line if all you had was //?)  And I also don't like leaning that much on editor features.

Sorry to ask a question with overtones of an opinion poll, or about something subjective.  But what I'm looking for are any more objective arguments I am not thinking of, which could provide more ammunition backing this feature I think is important.  (Or I guess I could accept a powerful argument favoring NOT having a multi-line comment format, which overrides my strong desire to have it... I'm not putting high odds on that, though.)

答:
I don't see a compelling argument here for non-line comments, and personally I cannot remember the last time I've used one.

Comments in and of themselves are decreasing in frequency, and should be focused on explaining why code is doing stuff. That is done using line comments.

Leaving commented code in your codebase is an anti-best practice with the ubiquity of source control systems (and distributed systems make it even easier).

Multi line comments aren't going to make or break your programming language.

We're not using stone knives and bearskins anymore. When I first started, not a few programmers used vi (not even vim) because things like syntax highlighting were a crutch. Programmers use tools, take advantage of that.

ContentLicense: CC BY-SA 4.0


问:
Understanding object-oriented programming: why is it important?
Just started learning about classes in C++ and I'm have trouble understanding why object orientated programming (OOP) is useful. I understand the syntax, how to use them etc.

But I'm still confused as to why OOP is advantageous. Here are some specifics I'm having trouble with:

Private variables. What is the use? Many sources tell me its to prevent outsiders from changing internal variables of the object, to protect the "insides". That doesn't make sense to me because wouldn't someone who wanted to change the variable just call the setter (mutator) functions and change it? Anyone can open the source file and call the setter and change the value of the variable. How is that "protection"? It's also mentioned that it makes debugging easier because instead of looking for every instance of the variable "x", you know "x" is only accessible through the class. So instead of ctrl+F "x" you just ctrl+F "memberFunction"?? How does that make debugging easier?

I read somewhere that using getters and setters is bad. Although sometimes unavoidable, its generally bad. I read "Don't ask for the information you need to do the work; ask the object that has the information to do the work for you." Can someone explain why this is important?

The big picture. I don't understand why implementing objects is more efficient than just if-statements and function calls....when there are functions in objects too. Objects don't seem to save tons of time in terms of coding. What am I missing?

答:
Note that you are assuming a setter always exists and can be modified. In some places, back-end code will be separate from front-end and there are only some ways to contact the back-end. In this case, private variables can be used to hide internal details from those using the code. This is highly important as a lot of code will exist in mult-tier environments where there may be a back-end platform that is separate from a front-end UI. Debugging can be easier because one can look for where the variable is used rather than having spaghetti code if properties get overly used or abused.

This relates to the idea of what methods does the class do and what can be done outside of the class. Overusing properties can lead to a lot of code duplication that can cause problems if one wants to change the internal details of the class.

How big is the largest coding project you've done? Have you programmed a shopping cart system with users and products? Without classes, how would you keep track of all the data that someone has in a cart? How do you handle the fact that the data from the database may contain relations that are better represented as objects than using a bunch of primitives that could get complicated as if you had lists for the names of products, prices of products and descriptions, a sort of any one list would trigger the others to also be sorted or else the data gets put into the wrong order.

ContentLicense: CC BY-SA 3.0


问:
I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett,  Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle".

I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here.

As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags.

I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!

答:
It is interesting what different approaches people take. I'd do the following:

Based on all the tracks played so far, give each one a score. Play the track with the lowest score (or, in the case of identical scores, a random one matching the lowest score). Repeat.

The difficult bit, of course, is giving a score. For each possible track you might play next, you would have to go through each (or a limited number of) tracks you have already played. If the [possible next] track and [recently played] track have something in common, you add to the score, depending on how much they have in common, what they have in common, and how long ago the [recently played] track was played. You would probably want "nothing at all in common" to be 0, so you can start off with all tracks as 0.

You will probably want to experiment with some hand-crafted playlists to begin with, to get the maths right - do you want the number of words in common, or the square of the number of words in common, or the square root of the number of words in common? Run your entire playlist through, see which ones float to the top as being "most in common", and hand-tweak the factors to get the balance right. Maybe you want to go per-letter, so "Duke Ellington" has a high score when compared to "Duke Elington", but an even higher score when compared to "King Elle Duton" (if I haven't lost any letters :). You should consider very carefully which fields you want to compare, and if you want to compare between fields. You might even consider bigrams (pairs of letters; in the case of Duke ellington, "Du","uk", "ke", "ee", and so forth.

Note that, if you have a lot of a particular artist, that artist might be dropped down in priority - you might hear a track by a unique artist 5 times, before you hear all 10 of your Duke Ellington tracks. This might or might not be what you want. You could avoid this by setting up a dictionary of everything you have to compare, and how often they occur, so if you have lots of Duke Ellington tracks, two tracks that are by Duke Ellington are "less similar" than two by Billy Joe Shaver.

It might even be worth pre-caculating a table with every combination of two pairs of songs. Also, when considering which song to play next, you only need to remember the best song so far; if the next one to consider has a worse score than the best song so far, you can skip to the next.


问:
Practical Primes In P
Or rather, practically applying PRIMES in P.

I've heard a lot about "PRIMES in P", or the "AKS algorithm". It is, to oversimplify slightly, a very fast way of finding prime numbers.

However, while I've tried reading the original paper (the revised "V3" seems to have vanished from the internet), it's a bit above my comprehension.

I've also tried using Google to find practical implementations of the algorithm, but they too are incomprehensible (which is to say, they're all written in comment-free C++).

Can someone produce a hobbyist/freshman-level explanation of how to implement the AKS algorithm? Or am I misinterpreting exactly what it it does and is for?

答:
First, let me discuss AKS.  AKS is very important for the theory, but not used in practice.  It is not fast, and it isn't a usually used "way of finding prime numbers" ala a sieve.  It is a primality test -- that is, given a number N, it answers deterministically whether N is prime or not.  There are other methods that run millions of times faster (e.g. BPSW or deterministic M-R below 2^64, APR-CL or ECPP above).  This is even assuming you need a proof -- BPSW plus some M-R tests are good enough for almost everyone and will be faster yet.

The internet loves AKS because it sounds like it should be fast.  The only known deterministic polynomial time algorithm!  This is caused by a misunderstanding of randomized algorithms and a failure by the posters to actually implement or even use these methods in practice.

AKS, from Wikipedia or the v6 paper, is straightforward at the high level.  There are a few gotchas like making sure you do the logs correctly, and some implementation efficiencies in steps 2/3.  Implementing znorder correctly isn't too hard, especially if you are lax and don't worry too much about efficiency yet (step 5 completely dominates the time).  Step 5 is tricky, because you have to do efficient polynomial exponentiation modulo N and a polynomial.  I'd say first get it done and working, then worry about efficient solutions like binary segmentation.

There are lots of implementations around. Programming Praxis has a nice blog post about it, with discussion and a couple implementations.  See Part 1 and Part 2.  Part 2 shows implementation of the "V6" algorithm (the updated algorithm from the original authors).

Bornemann's implementation in Pari.  One of the fastest, uses some improvements and a cool r/s heuristic.

Programming Praxis has an relatively inefficient version in Scheme.  Easy to follow and the author explains every step.

Someone posted a nice Python version on Programming Praxis, albeit it only works up to 8 or so digits.

I have Perl, C, and C+GMP versions on github, with three algorithms each.  The V6 version is the one from the updated paper.  The Voloch+Bornemann version includes the improvements Bornemann shows, and until I implemented the third version, was the fastest open source implementation of AKS.  The third version uses theorem 4.1 from Bernstein's 2004 paper, which includes most published optimizations.  It is >10x faster than the Voloch+Bornemann version.

Yijun Yuan has a very readable version on github implementing the v6 algorithm using NTL.  It's not fast, but it's quite easy to follow from the paper.

There are many really bad versions out there (as there are of almost every algorithm one can think of).

One problem with AKS is that you give it a number, it churns away, and says "Prime" or "Composite".  I have seen many implementations that give the wrong answer for some inputs (due to a bug in the implementation).  Think about that.  This is supposed to be a proof -- after all, we ran the input through some Miller-Rabin tests, maybe BPSW, we're almost positive the number really is prime, and now we have decided we want as close to 100% certainty as possible.  Yet if we have no good assurance that the program has run correctly, what was the point?  This is why I think ECPP is a far better choice for primality proofs, since it gives a certificate that can be quickly independently checked at any time.  Given that it is also millions of times faster than AKS, it's an easy choice.

Title: Practical Primes In P


问:
Loose Coupling Presenter to View in MVP
We work in a Java shop here and our web application uses an implementation of the MVP architectural pattern. Our manager comes from a .NET world, where he has been exposed to the MVVM design pattern. Our manager is advocating changes in our MVP implementation, including that the Presenters should be decoupled from (or loosely coupled to, depending on your interpretation) its Views via the Observer design pattern, in tradition with MVVM. I am more of the opinion that the Presenter and the View work together to achieve a common goal, and as such should be coupled.

Among the arguments brought up in support of the change is the ability to unit test Presenters. If the Presenters only see the views as Observers, the argument goes, then they can be more easily unit tested. But presenters strongly coupled to their views are not necessarily difficult to test. If the View uses the Humble View paradigm, then it can be mocked. And finally, testability should be a symptom of good design, not a driver for the design.

Another argument used by my manager in support of layering the Views and the Presenters is the supposed maturity of MVVM. As such, we should follow MVVM's teachings and adapt to its implementation of MVP. Correct me if I'm wrong, but MVVM imposes the (artificial) layering of views and presenters in order to facilitate its data bindings in controls.

Can you please help us see the light here? Why should we use a decoupled model and pay the price for it? I'm not seeing the benefit. Occam's razor says I need arguments to use decoupling, and testing doesn't seem to be one of them.

Clarification: What I'm really looking for with this question are the arguments that can tip the balance in favor of a presenter that doesn't know about its view and shoots events in the aether or in favor of a presenter that knows about its view(s) through more direct coupling, like a humble view interface or directly to the class. Note that presenters can easily serve multiple views with both loose and tight coupling. The difference is in the interface that the presenter talks to: with loose coupling, the presenter talks to listener classes (or an event bus representative), whereas with tight coupling, the presenter talks to the view interface.

答:
I apologize to be the one to tip the argument against you. You are right, one strength of MVVM is it's ability (if implemented correctly) that you do not have to manually synchronize your data.

I would also have to agree with the testing being easier with MVVM.

For more arguments against or for, I would have to say that another strength of MVVM is that you can have more than one View Model for multiple Views.

So top three reasons for MVVM over MVP I would have to say is:

Data Binding

Testing

Multiple Views can use more than one View Model - Meaning you don't have to create a Presenter for every view.

After that the benefits become minor, and I feel that comfortability in the design you are using would out weigh those benefits. However, It is good to stretch and spread out into uncomfortable areas of design and programming, it broadens your horizons.

Title: Loose Coupling Presenter to View in MVP


问:
Advice for simple communication protocol (iPod and Arduino)
I connected iPod with Arduino using serial (UART) connection. Arduino sends 0-1023 number (so it's two bytes) as it's samples light sensor value.

I'm asking about advice about simple and reliable communication protocol.

Do I need magic constants to start/stop communication.

Maybe I need sent data of small chunks.

Now I have:

```<code>while (1)
{
   data = getData() ;
   // two bytes of 0-1024
   Serial.write((data) & 0xFF)) ;
   Serial.write((data) & 0x300)) ;
}
</code>```

Any suggestion how to implement simple and reliable protocol ?

Image of my device: http://cl.ly/image/051f370v3e0g

Thanks

答:
Without doing research on the topic, I would suggest the following. So, can you rapidly send the the two bytes? If so, I would break down your code into base 512 from binary, and use the following numbers for special commands. Such as...

514 = New Data Stream
DATA CHUNK
DATA CHUNK
DATA CHUNK
DATA CHUNK
...
513 = Stop Data Stream

Then convert back to binary and deserialize into a memory stream or something. This would leave you with a vast amount of basic commands to communicate with such as

EVENT#1 - 600
EVENT_PARAMSTART = 550
Param Chunk #1
Param Chunk #2
EVENT PARAMSTOP = 551
EVENTEND = 599

Does that help or am I totally off base? XD


答:
There are several reasons to have a protocol, even a very simple one.

Reduce risk of errors, perhaps when the device is connected, started, stopped

Allow for future expansion: perhaps the device sends two kinds of data in the future

Make sure you're reading from the right device and not something different.

Helps debugging if you can see a stream you can recognise.

There are some advantages in using ASCII chars, if you want to debug. I'll do it in binary, and include a length byte.

I would suggest a simple protocol of 6 bytes. Say:

```<code>Serial.write(0xc5); // start
Serial.write(0x06); // total length of packet
Serial.write(0x01); // 1=temperature data
Serial.write(data & 0xff); // low byte of data
Serial.write((data >> 8) & 0xff)); // high byte of data
Serial.write(0x5c); // end
</code>```

Simple, easy to code, expandable. That would be my recommendation.

Here are some notes on my choices for these items.

The start byte (0xc5) is a distinctive bit pattern, relatively unlikely to occur by chance, in which half the bits are off and half on. That makes it relatively easy to find with debugging tools including an oscilloscope.

The end byte is the same reversed, for similar reasons.

Including the length is the simplest kind of check for framing errors or dropped bytes. If the start byte, end byte and length match the packet is probably valid.

The command byte of 0x01 allows room for expansion with future packet types. All packets should take the form c5,length,cmd,data...,5c.

The data is sent in little-endian format, which may be easier for some servers to read. Please note the correct use of shift-mask.

As suggested in a comment, the additional of a simple checksum would improve the likelihood of detecting errors over a noisy line. A simple rotating XOR should be sufficient, and easy to code.

Title: Advice for simple communication protocol (iPod and Arduino)

Body:
I connected iPod with Arduino using serial (UART) connection. Arduino sends 0-1023 number (so it's two bytes) as it's samples light sensor value.

I'm asking about advice about simple and reliable communication protocol.

Do I need magic constants to start/stop communication.

Maybe I need sent data of small chunks.

Now I have:

```<code>while (1)
{
   data = getData() ;
   // two bytes of 0-1024
   Serial.write((data) & 0xFF)) ;
   Serial.write((data) & 0x300)) ;
}
</code>```

Any suggestion how to implement simple and reliable protocol ?

Image of my device: http://cl.ly/image/051f370v3e0g

Thanks

Body:
There are several reasons to have a protocol, even a very simple one.

Reduce risk of errors, perhaps when the device is connected, started, stopped

Allow for future expansion: perhaps the device sends two kinds of data in the future

Make sure you're reading from the right device and not something different.

Helps debugging if you can see a stream you can recognise.

There are some advantages in using ASCII chars, if you want to debug. I'll do it in binary, and include a length byte.

I would suggest a simple protocol of 6 bytes. Say:

Serial.write(0xc5); // start
Serial.write(0x06); // total length of packet
Serial.write(0x01); // 1=temperature data
Serial.write(data & 0xff); // low byte of data
Serial.write((data >> 8) & 0xff)); // high byte of data
Serial.write(0x5c); // end

Simple, easy to code, expandable. That would be my recommendation.

Here are some notes on my choices for these items.

The start byte (0xc5) is a distinctive bit pattern, relatively unlikely to occur by chance, in which half the bits are off and half on. That makes it relatively easy to find with debugging tools including an oscilloscope.

The end byte is the same reversed, for similar reasons.

Including the length is the simplest kind of check for framing errors or dropped bytes. If the start byte, end byte and length match the packet is probably valid.

The command byte of 0x01 allows room for expansion with future packet types. All packets should take the form c5,length,cmd,data...,5c.

The data is sent in little-endian format, which may be easier for some servers to read. Please note the correct use of shift-mask.

As suggested in a comment, the additional of a simple checksum would improve the likelihood of detecting errors over a noisy line. A simple rotating XOR should be sufficient, and easy to code.


问:
What is a "markdown-formatted" README file on Github?
It's unclear to me what the format is, if there's systematic/command-line requirements for creating it, etc.

Basically, just to need to know the specs, and if there's technical steps for generating the README file.

答:
It's very strange, but it looks as though GitHub doesn't use GitHub-Flavoured Markdown (GFM) when rendering a README file.

GitHub uses "GitHub Flavored Markdown," or GFM, across the site--in issues, comments, and pull requests.

Instead it seems to use a version called redcarpet as part of the GitHub markup project. They also support several other markup formats, including MediaWiki. Just use the right file extension, and GitHub will render the markup.

If you want to see the differences between the two different flavours of Markdown, read the description of GFM and its extra features.


问:
How can I promote software reuse in a large company?
Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>

答:
become the CIO

promote software reuse

profit!

ContentLicense: CC BY-SA 2.5


问:
Kerberos web authentication
I'v developed an internal singe-page web-app (unix, apache & postgresql) protected by a simple login page. Currently, the users have their own login role with a password.

This is starting to get cumbersome for a couple reasons:

Users have multiple passwords (for my web-app and Active Directory, the company-network is windows).

Storing user information in two different places (would like to centralize).

I've been looking into Kerberos to the point, I've set-up a KDC and am able connect to the database through GSSAPI authentication (command-line only).

From what I understand I should be able to use my own KDC that will integrate with Active Directory.

My problem I'm working through at the moment is web-app authentication via kerberos:

If a user is on the web - how can I obtain/verify kerberos credentials? Can I store the credentials in a cookie? Do I have
        to resort using OAuth,Webauth, or something similar?

To clarify, What I want to do is:

If a user doesn't have valid credentials, give them the login page to obtain credentials (via kinit, but how through the browser?) and return valid credentials.
         (how can I store credentials in browser, can I create a cookie from the Kerberos credentials?).

I've googled, and read a fair-few pdf's and web-resources, but unfortunately none of them were able to dumb it down enough for me to get a solid grasp of how to accomplish kerberos web authentication.

If you didn't notice, I'm confused on how to piece everything together and would appreciate a conceptual over-view of how everything fits together.

答:
Simplify. Have you considered using AD's LDAP interface and performing an ldap_bind against the user with the given password? This is a very easy way to validate user credentials against an AD server without storing the password or adding extra layers.

Apache even has an auth plugin that does this bit for you: http://httpd.apache.org/docs/current/mod/mod_authnz_ldap.html or https://httpd.apache.org/docs/2.0/en/mod/mod_auth_ldap.html

Kerberos is great for those times when you don't want to prompt the user for their password (you request a token from the daemon running in their environment instead). I've not seen this working with web apps before; I imagine it would require the app to break out of the browser's sandbox.

Title: Kerberos web authentication


问:
How to discover a class in PHP dynamically much like a plug-in architecture
I'm encountering a common issue in PHP (and most other languages) at the moment, where systems I'm designing need to be updated in multiple places to add new features, whereas I would like to have a core, where I can add new features, plugin's etc without having to touch the core code.

An example would be a a navigation menu, where the menu loads it's items from directory or namespace X. My aim is so once I or another developer adds a new file, extends a MenuItem class, whichever it needs to be, the class loading the menu would discover this new file and display it, without ever having to touch the core menu loading code.

The best I have come up with so far is:

```<code>function get_menu_items() {
    $menu_items = array();
    $raw_files = scandir(DOCUMENT_ROOT . '/menu/menu_items');
    foreach($raw_files as $file){
        require_once($file);
        $class_name = substr($file, 0, -4); // cut away the '.php'
        $menu_items []= new $class_name();
    }
    return $menu_items;
}
</code>```

But the above feels wrong as I shouldn't be checking a directory for existence of files for features! I imagine this is a common design pattern like wordpress would use for plugin discovery? I've been searching for a while but not been able to better the above! Any help would be greatly appreciated!!

答:
Even tho your solution works fine in principle, it's extremely slow because of using the File-system API and quite vulnerable I'd say. For example, in theory, I can use your upload profile photo form to inject a PHP file with .jpg extension and move it into your plug-ins directory and let your application load it for me.

You might not notice the slow-ness of using the file-system api -- on a simple website/CMS with couple of online users at the same time, and no one might even try to attack your web application at all, however if you're looking for a Robust solution, I highly encourage you to come up with a solution that gives you Control over what files are being used/loaded by your script.

As an example you can store all of the new plug-ins in a JSON file and use that file as a valid source of installed plug-ins for your script. In this way what you really need is to add the file to the directory and then just add a simple key/value pair to your JSON file. It won't really take that much time, however it will gives a lot piece of mind I'd say.

A database-based solution could be a better idea if you need to let a none-technical person to choose between the plug-ins, however in your example it might be an overkill.


问:
What are some good, simple examples for queues?
I'm teaching CS2 (Java and data structures), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are multithreaded message passing (but MT programming is out of scope for the course), and BFS-style algorithms (and I won't be covering graphs until later in the term).

I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last N items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature.

Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?

答:
In teaching data structures, I usually use the application of the bank queue simulation where customers wait in a queue and there are a number of service windows.

The problem is to simulate the process in order to find out statistics of the following: customers waiting time in the queue (max, min, average), and numbers of customers waiting in the queue. I use a predefined frequency of arriving new customer every minute of a day and an average service time of a customer on the service window with values from the random number generator.

The result will be recommendations for the optimal number of service windows and the optimal number of chairs in the waiting hall that would guarantee customer satisfaction. Very interesting application to students.


问:
Java Communcation API not available for Windows
I want to write a program in Java using RS-232. But I am unable to find the java.comm Package for the windows. Which library should I use for this purpose?

http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

The only package avaiable here are not for Windows. Can you please guide me as I am new to this kind of development.

Using rxtx + java I got this code from the internet

```<code>import java.util.Enumeration;
import gnu.io.CommPortIdentifier;
public class SimpleWrite
{
public static void main (String args[])
{

    Enumeration port_list = CommPortIdentifier.getPortIdentifiers();
    System.out.println(port_list);

    while (port_list.hasMoreElements())
    {
        CommPortIdentifier port_id = (CommPortIdentifier)port_list.nextElement();

        if (port_id.getPortType() == CommPortIdentifier.PORT_SERIAL)
        {
            System.out.println ("Serial port:" + port_id.getName());
        }
        else if (port_id.getPortType() == CommPortIdentifier.PORT_PARALLEL)
        {
            System.out.println ("Parallel port:" + port_id.getName());
        }
        else
            System.out.println ("Other port:" + port_id.getName());
    }
}
}
</code>```

But this code gives me error of gnu.io.rxtx.properties has not been detected.

答: There are several libraries written for this, just google for rxtx + java. One of the alive ones seems to be http://code.google.com/p/java-simple-serial-connector/ .


答:
I going to go further than "Yes, they should be in" and say they're a basic requirement for any modern language and something I would just expect to work, at least 2 levels, preferably // and /* */ since that's what most developers are used to.

While I agree with @Telastyn that:

Leaving commented code in your code base is an anti-best practice with
  the ubiquity of source control systems (and distributed systems make
  it even easier).

The IDE & language I use at work (Embarcadero Delphi) has 3 kinds of comments "//, { } and (* )", which can be nested: // in { } and { } in ( *).

Even CSS and HTML have multi-line comments!

It sounds as though in this case the designers aren't producing an IDE and editing will be done in a 3rd-party test editor.

In this case there's another important point, not all text editors are created equal, although most modern editors provide these kinds of facilities (not always with keyboard shortcuts), sometimes you may not have access to them or don't want to open a programmers editor to make a small tweak.

It all comes back to developer (as the customer in this case) productivity.

Multi-line comments can be hugely useful during development when trying things out, re-factoring or almost any other development task, especially when you need to change things in multiple places at once just to see if something works.

They can also be useful when adding comments to the top of a source code file, such as legal/copyright notices, dates of major/important changes (not a substitute for good commit comments) or anything else that may be useful to have prominently displayed at the top of the file for at-a-glance reference.

Title: Are multi-line comments a critical facility in a modern language?

Body:
I'm trying to convince the designers of a language that multi-line comments with an arbitrary start and end are important, and should be included.  Currently there is only a "comment-to-end-of-line" primitive.

Their line of argumentation reminds me of what some say about why you should use spaces instead of tabs.  Basically that editor features can pick up the slack and remove the requirement for a different construct.  (So if you wanted to comment out more than one line, you'd select what you wanted and run a macro of some kind...to add or remove a to-end-of-line comment to each line.  I just read that this feature exists in Visual Studio, despite C/C++ offering a multiline comment.)

Other suggestions about removing blocks of code from execution wind up being things like "cut the code out, try it, and use the redo queue".  I think this is not a very easy way to keep track of "invisible" information you might want back, and redo queues are quick to lose information the moment you hit even a stray key on accident.  So this does not sway me.

I can live with the space vs. tab thing and putting that on the editor, and it's now pervasive.  But to me this is different, and I'm dissatisfied with these answers.  For me, being able to comment out code with just a start and end marker like /* and */ is extremely useful.  Passing the buck to editor magic doesn't let you position your starts and ends arbitrarily (how would you comment out the middle of a line if all you had was //?)  And I also don't like leaning that much on editor features.

Sorry to ask a question with overtones of an opinion poll, or about something subjective.  But what I'm looking for are any more objective arguments I am not thinking of, which could provide more ammunition backing this feature I think is important.  (Or I guess I could accept a powerful argument favoring NOT having a multi-line comment format, which overrides my strong desire to have it... I'm not putting high odds on that, though.)


问:
Organising models in ASP.NET MVC
I'm building websites in ASP.NET MVC and I quickly figured out that my models are getting harder to organise as they grow.

What I normally do is create one model to add and edit data. But in my add view I have 2 extra properties. So I'm re-using the same model with 2 extra properties but I don't use these my edit view.

Now I have a few questions regarding this.

How do you organise it?

Do you create one file class with multiple models in it or is it better to create a new file for each model?

Is it better to create a new model if you need a few more properties?

答:
I don't recommend putting multiple classes in a single file. One file, one class, one responsibility.

With regards to the models, I would encourage people to create a new model or create an abstraction with common properties and then inherit from that abstraction. So you'd have an abstract class and two classes inheriting from it.

Title: Organising models in ASP.NET MVC


问:
What is a good pattern for combined caching and reinitialization?
I have a situation where I have three requirements:

Lazy initialization - don't create the collection until asked for it

Caching - keep the collection in memory on the object

Reinitialization - be able to reinitialize the collection when desired, instead of simply getting the existing results.

This is simply an optimization inside a single class - it is not loading anything from a database and ideally I'd like just a good method design pattern for this, not a multiple-class design.

Usually for lazy initialization I'd have this:

```<code>Collection getCollection() {
    if (collection != null) {
         // generate and set collection
    }
    return collection;
}
</code>```

But now I'm having trouble deciding on the best way to provide for reinitialization of a fresh collection and getting that collection.  A fresh boolean parameter would work, but adding a parameter to a getter doesn't seem to feel right (maybe that's the Java in me talking — I could be convinced).

答:
I would add an extra method instead of passing a boolean parameter:</p>

```<code>Collection getFreshCollection()
{
   collection = null;

   return getCollection();
}
</code>```

Body:
I would add an extra method instead of passing a boolean parameter:

Collection getFreshCollection()
{
   collection = null;

   return getCollection();
}


答:
Code that you produce might be consumed by third parties. As it's your code, it seems odd to you that you have to hide implementation details through private properties and methods. When you give this code to somebody else, they don't need to know how your code works, instead they need to know what it does.

In order to expose the "what it does" bit, you use public access modifiers. Imagine a vending machine. You drop a coin, select a product and the machine gives you a fizzy drink. Do you really need to know how the machine works? You don't all you care about is that you get a product after you put money in and press the button.

With regards to the setters and getters - yes, you can make them public. As soon as you do that, you expose implementation details to the consumer. Imagine you have three private properties and a method called "ServeDrink". You might choose to expose all three properties and a method through a public access modifier. You give this to somebody else. That person (consumer) looks at your API, sees public properties and starts using them freely. A month later, you decide to change how this works, there is still a function for serving a drink, but you no longer want to have three properties, instead you bring in a single property that aggregates old three properties. You give this to consumer.

Consumer of your API is now faced with a problem, where he though that it's OK to use three public properties, when it wasn't the case. Having said all this, you can try thinking of a consumer as an end user. By using OO design, you set limitations and boundaries on how your API should be used. You also state clear responsibilities. E.g. if something is public, you intend the consumer to use it, and if it's private, than the consumer shouldn't even be aware of it.

Try reading this story http://steve-yegge.blogspot.co.uk/2006/03/execution-in-kingdom-of-nouns.html - it's a fun read comparing function and OO kingdoms.

Title: Understanding object-oriented programming: why is it important?

Body:
Just started learning about classes in C++ and I'm have trouble understanding why object orientated programming (OOP) is useful. I understand the syntax, how to use them etc.

But I'm still confused as to why OOP is advantageous. Here are some specifics I'm having trouble with:

Private variables. What is the use? Many sources tell me its to prevent outsiders from changing internal variables of the object, to protect the "insides". That doesn't make sense to me because wouldn't someone who wanted to change the variable just call the setter (mutator) functions and change it? Anyone can open the source file and call the setter and change the value of the variable. How is that "protection"? It's also mentioned that it makes debugging easier because instead of looking for every instance of the variable "x", you know "x" is only accessible through the class. So instead of ctrl+F "x" you just ctrl+F "memberFunction"?? How does that make debugging easier?

I read somewhere that using getters and setters is bad. Although sometimes unavoidable, its generally bad. I read "Don't ask for the information you need to do the work; ask the object that has the information to do the work for you." Can someone explain why this is important?

The big picture. I don't understand why implementing objects is more efficient than just if-statements and function calls....when there are functions in objects too. Objects don't seem to save tons of time in terms of coding. What am I missing?


答:
Any scheduling algorithm almost always involves a queue.

This can range from a simple first come first served queue to buffer request for a single consumer.

To a complex job scheduling queue where "tasks" can have priorities and "workers" have different capabilities.

A good use case to play around with could be  "You have a central print server with four printers attached two capable of color, one capable of printing double sided and one capable of printing on larger paper. Users can pay extra for a rush job, or, less if they don't mind waiting longer. You can incur penalties if you deliver late so you want as much throughput as possible."

Title: What are some good, simple examples for queues?

Body:
I'm teaching CS2 (Java and data structures), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are multithreaded message passing (but MT programming is out of scope for the course), and BFS-style algorithms (and I won't be covering graphs until later in the term).

I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last N items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature.

Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?


问:
Why did Facebook use C++ beside PHP?
What is the main reason that made Facebook need to use C++ beside PHP? I am wondering if I make a website with alot of vistors would I need to use C++ as well? </p>

答:
The C++ element used by Facebook is the HHVM.

That is the HIPHOP virtual machine. Although written in C++ it is essentially a "better PHP interpreter".

The php code is compiled into byte code which is then interpreted by the HHVM at execution time and is subject to "Just In Time" optimizations as it runs.

The developers at face book still write mostly in PHP, and, what you see on your browser is almost certainly output by a PHP program -- allbeit on  which has been compiled and interpreted by the HHVM runtime.

The actual HHVM is freely available open source. So if you do need to serve one million cute kitten pictures per hour then you can download the HHVM and speed up your server with minimal change to your PHP.

Title: Why did Facebook use C++ beside PHP?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Learn from your lesson and sign a contract!

Contracts are great. They put everyone on the same page and cover all the nitty gritty details that "feeling someone out" can't.

My contracts include provisions for the following things that may be helpful in your case:

Ownership: This specifies that until the client pays for the site in full as indicated on the final invoice, I own the code. Having a signed document for this leaves you with the power to pull the site and the client with little power to pursue you for damages.

Payment: I spell it out in the contract that the price quoted is not always the final price. Changes in scope add to the billed hours, and this will be reflected on the final invoice. Payments are due in 30 days of contract signing and every month late the client pays incurs a %5 of balance fee plus $50 (charging for the time it takes to send emails an deal with nasty clients who don't want to pay).

Liability: If the client does decide to hire a lawyer when you pull the site the contract stipulates that any legal action surrounding the transaction will be limited to the price of the contract. Essentially you will never have to give a client who sues you more money than they have paid you.

Do some research on contracts and don't ever start a project without one.

Good luck!

Title: How to get money from reluctant client?


答:
Perhaps an example can help explaining the benefits of object oriented programming.

Consider a linked list, it consist of node structures containing some data and pointing to other nodes:

```<code>struct Node {
    Node* next;
    int data;
}
</code>```

Assume a list of these (I named them for convenience):

```<code>Node c{null, 4};
Node b{&c, 73};
Node a{&b, 42};
Node* list = &a;
</code>```

You can use this list as follows:

```<code>std::cout << list->data; // prints 42
std::cout << list->next->data; // prints 4
</code>```

All is fine here, but imagine somewhere in your program the following happens:

```<code>Node d{&a, 17};
list->next->next = &d;
</code>```

Now the list is messed up, it is: [a, b, d, a, b, d, …]; node c is lost and the list has become an endless repetition.

1a

To answer the first part of part 1 of your question, when Node::next is private the problematic assignment list->next->next = &d; can not happen.

1b & 2

Given a public setter:

void Node::setNext(Node* new_next) {
       this->next = new_next;
   }

As you say, then anyone can just use list->next->setNext(&d);.  This leads to the answer to part two of your question: having a setter setNext() is bad.  Lists should have modifying operations like insert(value), append(value), and remove(value).

This is an example of the general rule: classes should have operations that fit their intended meaning and use, not getters and setters for every field the implementation happens to have.  Or the version you read: "Don't ask for the information you need to do the work; ask the object that has the information to do the work for you."

3

Your question, "I don't understand why implementing objects is more efficient than just if-statements and function calls", is a difficult one.  First the word 'efficient' can have two meanings:

the programs run faster and/or consume less resources

writing a program takes less effort

For the first point running faster or consuming less resources, both object oriented programs and programs using if-statements and function calls can be efficient in this sense or very inefficient.  For some problems thinking about them in an object oriented manner, leads to a more elegant and efficient solution than the if-statements and function calls approach.  For other problems object oriented programming just gets in the way and causes overhead.

On the second interpretation of 'efficient': writing a program takes less effort.

As @JB_King states object orientation helps to organize things that belong together.

Once you have the list class, in other parts of the code you can think in terms of maintaining a list of 'x'es and sending a list of 'y's, instead of pointer manipulations.  In addition when you look at the C++ standard library, the java runtime library, Boost Collection, Commons collections, Google guava, and others you'll find that others have already written List classes and that perhaps for your programming problem a list is not the best class but some other kind of collection.

So once you have (or someone else has) written a class you can reuse it and you do not have to write it again.
NOTE: of course the same holds for good libraries of functions, my answer is lacking a good explanation of why object oriented is better reusable than functional libraries.

Elaborations and side nodes

Even if you decide that this list class really does require a setNext()-method, then the method can have advantages over directly manipulating the Node::next-field.  The method can perform extra checks; e.g.:

Node:setNext(Node* newNext) {
       if (this->next == null)
       {
           this->next = newNext;
       }
       else
       {
           throw new Error();
       }
   }

Making fields private does not prevent malicious programmers/code from reading and manipulating the field; i.e.

```<code>class SecurityController {
private:
    std::string secretPassword;
};
</code>```

and

```<code>struct SecurityController2 {
    std::string secretPassword;
}
</code>```

are both equally (in)secure.

Declaring things private (and other methods of hiding implementation details) only helps well behaving programmers to create better code.

Initialization

Sometimes initializing an object is the only time that direct access to an object's fields is required.  Then you can define a constructor that accepts and sets the field, e.g.:

```<code>Node::Node(int value_) {
    this->value = value_;
}
</code>```

However, often there are better constructors that do not require the caller providing values.  For example:

```<code>List::List() {
    …
}
</code>```

to construct an empty List, and

```<code>List::List(std::iterator<int> start, std::iterator<int> end) {
    …
}
</code>```

to create a list containing copies of the values from the C++ STL range [start, end>.

Body:
Perhaps an example can help explaining the benefits of object oriented programming.

Consider a linked list, it consist of node structures containing some data and pointing to other nodes:

struct Node {
    Node* next;
    int data;
}

Assume a list of these (I named them for convenience):

Node c{null, 4};
Node b{&c, 73};
Node a{&b, 42};
Node* list = &a;

You can use this list as follows:

std::cout << list->data; // prints 42
std::cout << list->next->data; // prints 4

All is fine here, but imagine somewhere in your program the following happens:

Node d{&a, 17};
list->next->next = &d;

Now the list is messed up, it is: [a, b, d, a, b, d, …]; node c is lost and the list has become an endless repetition.

1a

To answer the first part of part 1 of your question, when Node::next is private the problematic assignment list->next->next = &d; can not happen.

1b & 2

Given a public setter:

void Node::setNext(Node* new_next) {
       this->next = new_next;
   }

As you say, then anyone can just use list->next->setNext(&d);.  This leads to the answer to part two of your question: having a setter setNext() is bad.  Lists should have modifying operations like insert(value), append(value), and remove(value).

This is an example of the general rule: classes should have operations that fit their intended meaning and use, not getters and setters for every field the implementation happens to have.  Or the version you read: "Don't ask for the information you need to do the work; ask the object that has the information to do the work for you."

3

Your question, "I don't understand why implementing objects is more efficient than just if-statements and function calls", is a difficult one.  First the word 'efficient' can have two meanings:

the programs run faster and/or consume less resources

writing a program takes less effort

For the first point running faster or consuming less resources, both object oriented programs and programs using if-statements and function calls can be efficient in this sense or very inefficient.  For some problems thinking about them in an object oriented manner, leads to a more elegant and efficient solution than the if-statements and function calls approach.  For other problems object oriented programming just gets in the way and causes overhead.

On the second interpretation of 'efficient': writing a program takes less effort.

As @JB_King states object orientation helps to organize things that belong together.

Once you have the list class, in other parts of the code you can think in terms of maintaining a list of 'x'es and sending a list of 'y's, instead of pointer manipulations.  In addition when you look at the C++ standard library, the java runtime library, Boost Collection, Commons collections, Google guava, and others you'll find that others have already written List classes and that perhaps for your programming problem a list is not the best class but some other kind of collection.

So once you have (or someone else has) written a class you can reuse it and you do not have to write it again.
NOTE: of course the same holds for good libraries of functions, my answer is lacking a good explanation of why object oriented is better reusable than functional libraries.

Elaborations and side nodes

Even if you decide that this list class really does require a setNext()-method, then the method can have advantages over directly manipulating the Node::next-field.  The method can perform extra checks; e.g.:

Node:setNext(Node* newNext) {
       if (this->next == null)
       {
           this->next = newNext;
       }
       else
       {
           throw new Error();
       }
   }

Making fields private does not prevent malicious programmers/code from reading and manipulating the field; i.e.

class SecurityController {
private:
    std::string secretPassword;
};

and

struct SecurityController2 {
    std::string secretPassword;
}

are both equally (in)secure.

Declaring things private (and other methods of hiding implementation details) only helps well behaving programmers to create better code.

Initialization

Sometimes initializing an object is the only time that direct access to an object's fields is required.  Then you can define a constructor that accepts and sets the field, e.g.:

Node::Node(int value_) {
    this->value = value_;
}

However, often there are better constructors that do not require the caller providing values.  For example:

List::List() {
    …
}

to construct an empty List, and

List::List(std::iterator<int> start, std::iterator<int> end) {
    …
}

to create a list containing copies of the values from the C++ STL range [start, end>.


问:
Natural Language to Search Criteria - Date Ranges
Consider an application that stores a set of records that contain:

Description

Cost

Purchase Date

I'd like to be able to allow users to utilize natural language to search the dataset.

For example, the search expression:

blue from last month less than $20

would translate into (Linq as an example only - correctness of the query is not in question):

```<code>_db.Widgets.Where(w => w.Description.Contains('blue') && w.PurchaseDate >= DateTime.Now.AddMonths(-1) && w.Cost < 20)
</code>```

I'm struggling to find a starting point.  Any resources to get me in the right direction would be appreciated (I am working in .NET).

答:
"Natural Language" quicksand as far as computers are concerned. You will get bogged down ambiguous detail as soon as you enter. Which language? I suppose you mean English out of the several thousand available. Then which dialect of "English" you probably mean "East Coast University American" minus Jargon and Slang. So you end up with a limited vocabulary of "proper" English with a restricted grammar. Which ain't natural in the slightest.

"Dates" on the other hand are a minefield. What is "10/02/02" or "10/12/11"? Which calendar? There are several  to choose from its 2557 where I am sitting but the guy next to me thinks it's 1345.

This is why we have forms with pull downs and date choosers. They remove these ambiguities and with a little effort can be adopted to many languages and cultural conventions.


问:
Git alternative to a shelveset in TFS
I use git for my personal projects, so I have never run into any issues with Git, however I had a discussion at work today and its something that I haven't thought about.

In TFS you can store your changeset into a shelveset, this shelveset can be viewed by other developers, say for a peer review.

From what I understand in github you are working on your local copy of the repo (possibly with custom branches for different features) and then comes a point for a peer review. How would you go about sharing a specific changes on your local repo with someone else?

答:
Some options:

You could run an instance of gitweb to allow others to view your changes

You could distribute patch sets of your changes for review

You could push your changes to a shared central repo, in your own remote branch, where others can inspect your changes directly or in github.

Title: Git alternative to a shelveset in TFS


问:
Image coordinates calculation algorithm
I was looking at Jcrop library code for scaled image size calculation, but I couldn't clearly understand algorithm used in following function:

https://github.com/tapmodo/Jcrop/blob/master/js/jquery.Jcrop.js#L187

```<code>function presize($obj, w, h)
{
  var nw = $obj.width(),
      nh = $obj.height();
  if ((nw > w) && w > 0) {
    nw = w;
    nh = (w / $obj.width()) * $obj.height();
  }
  if ((nh > h) && h > 0) {
    nh = h;
    nw = (h / $obj.height()) * $obj.width();
  }
  xscale = $obj.width() / nw;
  yscale = $obj.height() / nh;
  $obj.width(nw).height(nh);
}
</code>```

I know that its using jquery image object and boxWidth and boxHeight as described on following link:

http://deepliquid.com/content/Jcrop_Sizing_Issues.html

But I want to understand the algorithm used.

答:
Lets break it down into pieces, shall we?

```<code>function presize($obj, w, h)
{
</code>```

Accept a jQuery object ($obj) with a resize width and height.  How do I know it requires a jQuery object?  Functions width() and height() aren't native for dom elements.

```<code>  var nw = $obj.width(),
      nh = $obj.height();
</code>```

Create two new variables corresponding to object's current width and height.

```<code>  if ((nw > w) && w > 0) {
    nw = w;
    nh = (w / $obj.width()) * $obj.height();
  }
</code>```

If object's current width is greater than resize width (and assuming resize width has some meaningful value), nw is reassigned to resize width w, and nh is assigned to a height proportionate to width resize (w / $obj.width() would be the proportion of new width with respect to old width.  If these were the same, it would be 1 and hence not chance height.

```<code>  if ((nh > h) && h > 0) {
    nh = h;
    nw = (h / $obj.height()) * $obj.width();
  }
</code>```

Do same for height, assuming new height is greater than resize height h and passed height is some meaningful value.

```<code>  xscale = $obj.width() / nw;
  yscale = $obj.height() / nh;
</code>```

Create or assign global variables xscale and yscale to inverse of newly created proportions.  In other words, if you halved width and height, xscale would be 200% and yscale would be 200%.  This is likely in order to know how to reverse the operation later, though that's just speculative.

This is a function side effect, and this is generally bad practice since it can be glanced over too easily, however I'd be lying if I claimed I never needed to do something of this nature.  Call me lazy.

```<code>  $obj.width(nw).height(nh);
</code>```

Attempt to assign object's new width and height to calculated width and height.  If this were an image, this would likely work out well, however, this is by no means guaranteeing that the resulting width and height will be the calculated width and height.

```<code>}
</code>```

Hope that helps.

Title: Image coordinates calculation algorithm

Body:
Lets break it down into pieces, shall we?

function presize($obj, w, h)
{

Accept a jQuery object ($obj) with a resize width and height.  How do I know it requires a jQuery object?  Functions width() and height() aren't native for dom elements.

  var nw = $obj.width(),
      nh = $obj.height();

Create two new variables corresponding to object's current width and height.

  if ((nw > w) && w > 0) {
    nw = w;
    nh = (w / $obj.width()) * $obj.height();
  }

If object's current width is greater than resize width (and assuming resize width has some meaningful value), nw is reassigned to resize width w, and nh is assigned to a height proportionate to width resize (w / $obj.width() would be the proportion of new width with respect to old width.  If these were the same, it would be 1 and hence not chance height.

  if ((nh > h) && h > 0) {
    nh = h;
    nw = (h / $obj.height()) * $obj.width();
  }

Do same for height, assuming new height is greater than resize height h and passed height is some meaningful value.

  xscale = $obj.width() / nw;
  yscale = $obj.height() / nh;

Create or assign global variables xscale and yscale to inverse of newly created proportions.  In other words, if you halved width and height, xscale would be 200% and yscale would be 200%.  This is likely in order to know how to reverse the operation later, though that's just speculative.

This is a function side effect, and this is generally bad practice since it can be glanced over too easily, however I'd be lying if I claimed I never needed to do something of this nature.  Call me lazy.

  $obj.width(nw).height(nh);

Attempt to assign object's new width and height to calculated width and height.  If this were an image, this would likely work out well, however, this is by no means guaranteeing that the resulting width and height will be the calculated width and height.

}

Hope that helps.


问:
Visitor only applicable when using the Composite pattern?
For a long time I've tried to get my head wrapped around the visitor pattern, and somehow this thing keeps being rather fuzzy to me.

I'm currently under the impression it is only useful to apply operations on objects that implement the Composite pattern. At least as far as PHP is concerned. Is that an accurate observation, or am I missing something?

I'm in the process of reimplementing some functionality, and this includes computing a diff between two Entities. These Entities contain various value objects. Different derivatives in the type hierarchy of these Entities have different value objects. Originally the diff code was contained in the entities themselves, though this caused quite some clutter, so I'd rather move it out into dedicated service objects. The Visitor pattern sprung to mind, though I do not see how I can actually sanely apply it. Would all the value objects need to implement some EntityElement interface? That seems bad. Is this a case where the Visitor pattern indeed does not apply, or am I simply failing to see how it would be applied nicely here?

答:
doOperation() = accept(), Element = Component

The difference is in the ObjectStructure in diagram 2. The Visitor Pattern does not require the ObjectStructure to implement the << interface >> Component. (Read below)

Often it is useful to let the ObjectStructure implement the Component interface in case you have a tree or other nested collections.

Sometimes you do not need an ObjectStructure to implement the Component interface. If the ObjectStructure is a simple collection, such as an array or a list, you know how to iterate over it. No need to add an accept() method to the ObjectStructure. It is the starting point of your visit.


答:
In Git, the basic model for pre-commit code review is to have a branch somewhere where it can bee reviewed, then merged with the main stream. This branch may be in the same repository as the main stream or in a completely separate one.

Some ways that I've seen done are:

Push a branch to origin, and have the reviewers merge the changeset in when they're ready.

Push a branch to a review repository or directly to the reviewer. Once reviewed the changeset may be pushed to the main repository.

Use a tool like Gerrit to "catch" pushes and hold them until they're reviewed. Once the right people have confirmed the changeset is ready, Gerrit will merge it into the main branch.

Using Github, Gitlab, Stash or another product, fork the original repository. Clone to your development machine and perform your changes. When finished, push to your fork and send a pull request to the original repository. This is the most common model in the open source world.

Title: Git alternative to a shelveset in TFS

Body:
I use git for my personal projects, so I have never run into any issues with Git, however I had a discussion at work today and its something that I haven't thought about.

In TFS you can store your changeset into a shelveset, this shelveset can be viewed by other developers, say for a peer review.

From what I understand in github you are working on your local copy of the repo (possibly with custom branches for different features) and then comes a point for a peer review. How would you go about sharing a specific changes on your local repo with someone else?


答:
In theory, each view should have its own Viewmodel. A Viewmodel (especially with a web-based UI) is your method of representing the relevant state or input from the View. With this in mind, there would be an edit Viewmodel and a create Viewmodel.

However, in practice, edit and create are nearly identical actions as far as the View is concerned. There's likely going to be very little difference between the screens (in this case, only two fields?), and they both generally represent the same object. I personally use the same Viewmodel for both views, despite a small bit of functional difference.
In general, I'd say the reason the fields aren't used is relevant to whether or not you should reuse the model. Reusing a Viewmodel to represent the same general data structure in two separate places is probably fine, but reusing a class just because it happens to have the right properties with the right names is breaking the pattern.

Regarding files, especially while using an IDE like Visual Studio that gives you a nice project explorer, it's best to keep one class per file. When the code is compiled, it makes absolutely no difference, so barring file system issues, this is a matter of usability and ease of programmer interaction. Also considering source control, where you might only be able to commit file-by-file, it's best not to lump more than one class together. When you change a class, you only one that one class to be considered "modified", but any other classes in the file would be included.

Title: Organising models in ASP.NET MVC

Body:
I'm building websites in ASP.NET MVC and I quickly figured out that my models are getting harder to organise as they grow.

What I normally do is create one model to add and edit data. But in my add view I have 2 extra properties. So I'm re-using the same model with 2 extra properties but I don't use these my edit view.

Now I have a few questions regarding this.

How do you organise it?

Do you create one file class with multiple models in it or is it better to create a new file for each model?

Is it better to create a new model if you need a few more properties?


答:
In a strongly-typed language, Visitor is useful because of "double-dispatch". Two objects of different types can interact without knowing what their types are. So it solves the "handshake problem": if I have a bunch of known types, I can have every type in the bunch shake hands with every other type. The magic it does to do that is double-dispatch: I call you, passing along important information without knowing your type, and then you call me back, adding your own information. Now everyone has contributed their part without revealing what type they are.

In a dynamically-typed language, I agree it doesn't seem like there's much point. There are simpler ways to traverse an object structure.

In a dynamic language, you might end up with a simplified version of Visitor that leaves out the double-dispatch.

In the case you mentioned, diff is a natural candidate for Visitor, because it has that "handshake problem": you have a bunch of types, and you want to diff any two of them. The simplification is that each class just needs to have a diff(other) method and a diff(value) method. The trick is that value doesn't have to be an integer -- it could be a more complex type. diff(other) would just be return other.diff(my_value). That's the double-dispatch part, which does the trick of hiding the internals of the class.

...

The only other pattern that comes to mind would be a "parametric polymorphism" soultion. You have a Diff class, and each class you have returns has a Diff diff() method. The Diff class contains whatever information you need to do the diff -- maybe just an int -- and its a common class that takes the specific types out of the equation. So it would look something like

```<code>Diff d = a.diff().apply(b.diff())
</code>```

If Diff really does just contain some value, then what you're really doing is putting the different objects on a number line, and you could just have that value as a property. E.g. a.scale() or a.rank()

Title: Visitor only applicable when using the Composite pattern?

Body:
For a long time I've tried to get my head wrapped around the visitor pattern, and somehow this thing keeps being rather fuzzy to me.

I'm currently under the impression it is only useful to apply operations on objects that implement the Composite pattern. At least as far as PHP is concerned. Is that an accurate observation, or am I missing something?

I'm in the process of reimplementing some functionality, and this includes computing a diff between two Entities. These Entities contain various value objects. Different derivatives in the type hierarchy of these Entities have different value objects. Originally the diff code was contained in the entities themselves, though this caused quite some clutter, so I'd rather move it out into dedicated service objects. The Visitor pattern sprung to mind, though I do not see how I can actually sanely apply it. Would all the value objects need to implement some EntityElement interface? That seems bad. Is this a case where the Visitor pattern indeed does not apply, or am I simply failing to see how it would be applied nicely here?

Body:
In a strongly-typed language, Visitor is useful because of "double-dispatch". Two objects of different types can interact without knowing what their types are. So it solves the "handshake problem": if I have a bunch of known types, I can have every type in the bunch shake hands with every other type. The magic it does to do that is double-dispatch: I call you, passing along important information without knowing your type, and then you call me back, adding your own information. Now everyone has contributed their part without revealing what type they are.

In a dynamically-typed language, I agree it doesn't seem like there's much point. There are simpler ways to traverse an object structure.

In a dynamic language, you might end up with a simplified version of Visitor that leaves out the double-dispatch.

In the case you mentioned, diff is a natural candidate for Visitor, because it has that "handshake problem": you have a bunch of types, and you want to diff any two of them. The simplification is that each class just needs to have a diff(other) method and a diff(value) method. The trick is that value doesn't have to be an integer -- it could be a more complex type. diff(other) would just be return other.diff(my_value). That's the double-dispatch part, which does the trick of hiding the internals of the class.

...

The only other pattern that comes to mind would be a "parametric polymorphism" soultion. You have a Diff class, and each class you have returns has a Diff diff() method. The Diff class contains whatever information you need to do the diff -- maybe just an int -- and its a common class that takes the specific types out of the equation. So it would look something like

Diff d = a.diff().apply(b.diff())

If Diff really does just contain some value, then what you're really doing is putting the different objects on a number line, and you could just have that value as a property. E.g. a.scale() or a.rank()


问:
Is it good practice to declare and set properties in abstract classes?
I am using PHP and designing some abstract classes.

I can declare properties with constant values within my abstract class and access/overwrite them from any class which extends this without re declaring them within any of the extending classes.

A benefit to this is less repetitive typing but the downside that overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely.

How is this handled in professional environments? I assume this has been thought out before and is either favored or isn't?

I am trying to adhere to good OOP principles/rules such as SOLID, DRY and KISS but I haven't seen this specific issue talked about in these. (perhaps I missed it when researching?)

答:
This may be a personal preference, but I avoid having base classes for the sake of sharing properties. Particularly in data classes. I don't mind the repetition, and I avoid locking my classes into a fixed "data" hierarchy.

There are enough problems with inheritance, particularly over time as the code base grows, that I am reluctant to share methods through a class hierarchy, and even more reluctant to share properties through a class hierarchy.

...

Hm. I just noticed that you mentioned "static" properties. Rather than static (i.e. global) properties in a base class, you're better off with a separate, single instance of something dispensed by a factory. Make sure you provide for concurrency to avoid race conditions.


问:
Purpose of `return self` from a class method?
I came across something like this in an open-source project. Methods that modify instance attributes return a reference to the instance. What is the purpose of this construct?</p>

```<code>class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self
</code>```

答:
As @Lie Ryan and @Frank Shearar mention, that's called a "fluent interface" but that pattern has been around for a really long time.

The controversial part of that pattern is that in OO, you have mutable state, so a void method has a kind of implied return value of this -- that is, the object with updated state is kind of the return value.

So in an OO language with mutable state, these two are more or less equivalent:

```<code>a.doA()
a.doB()
a.doC()
</code>```

...as opposed to

```<code>a.doA().doB().doC()
</code>```

So I've heard people in the past resist fluent interfaces because they like the first form. Another name I've heard for "fluent interface" is "train wreck" ;)

I say "more or less equivalent", though, because fluent interfaces add a wrinkle. They don't have to "return this". They can "return new". That's a way of attaining immutable objects in OO.

So you could have a class A that does (pseudocode)

```<code>function doA():
    return new A(value + 1)

function doB():
    return new A(value * 2)

function doC():
    return new A(sqrt(value))
</code>```

Now, each method returns a brand new object, leaving the initial object unchanged. And that's a way of getting into immutable objects without really changing much in your code.

Body:
As @Lie Ryan and @Frank Shearar mention, that's called a "fluent interface" but that pattern has been around for a really long time.

The controversial part of that pattern is that in OO, you have mutable state, so a void method has a kind of implied return value of this -- that is, the object with updated state is kind of the return value.

So in an OO language with mutable state, these two are more or less equivalent:

a.doA()
a.doB()
a.doC()

...as opposed to

a.doA().doB().doC()

So I've heard people in the past resist fluent interfaces because they like the first form. Another name I've heard for "fluent interface" is "train wreck" ;)

I say "more or less equivalent", though, because fluent interfaces add a wrinkle. They don't have to "return this". They can "return new". That's a way of attaining immutable objects in OO.

So you could have a class A that does (pseudocode)

function doA():
    return new A(value + 1)

function doB():
    return new A(value * 2)

function doC():
    return new A(sqrt(value))

Now, each method returns a brand new object, leaving the initial object unchanged. And that's a way of getting into immutable objects without really changing much in your code.


问:
Application use on website
Is there a good way to run a C# application on clientside in lieu of JavaScript? I have done some front end work with JavaScript and backend C# for web developing at an old job, but I am interested in hosting a website myself soon. I have a C# application I would like to be open source, but before people care to download I'd like them to be able to use it. At its basic level it's a simple text editor, but there's much more to it in the nitty gritty. I could write it in JavaScript, but it would require me to keep documentation and up to date changes on JavaScript and C# in that case.

I was thinking of creating an AJAX panel and somehow loading my winform application into a frame, but I don't know how or what words to google because I've never done it before except AJAX.

答:
What capabilities do you have in C# that you feel are missing from Javascript?  C# will run in a browser, but it will require your users to grant permission for a plugin.  You don't want that.

Learn and use Javascript.  Failing that, you can try writing an XBAP application.

Title: Application use on website


问:
How do open-source licenses work when the application is for internal use only?
I am writing a MATLAB application that makes fairly heavy use of the MATLAB File Exchange. Most of the functions I use from here fall under the BSD license.

My application is being deployed for internal use only and is not meant for public consumption. While my particular case uses code that falls under the BSD license, generally speaking what implications are there for using open-source code (GPL, BSD, etc) for programs that will never go public? Do I have to include a license file to cover the code that was licensed as BSD?

答:
The BSD has no source distribution requirements, other than you must retain the copyright notice on source distributions.

I would refrain from using such a license on an internal distribution, however.  The whole point of using the BSD license is to allow the widest possible distribution, and if your application is internal only, you're not going to need BSD.  Putting the BSD license on it implies that it is OK to use it anywhere, a notion that is not compatible with "internal only."


问:
Most Appropriate Authentication Type for MVC5 project
I am about to start a new ASP.NET MVC5 project and I am planning the authentication / authorization requirements at present.

The client wants Windows authentication, to prevent their users having to remember another new password. The site is web facing, so the downside would be an ugly pop up box asking for their credentials when they are accessing it offsite. Worse yet, on mobile, this box would be a problem.

The Active Directory Authentication options from out of the box are new to me, but after some reading appear to be more about controlling roles and authorization through your AD groups. I intend to keep all authorization concerns internal to the application.

Ideally, users will have Window authentication but with a nice login page where they can select their domain from a dropdown box and enter their domain login credentials. From some reading I thought possibly ActiveDirectoryMembershipProvider is the answer. However with the new available options I want to be sure there is not other options before blindly taking this route.

答: Well, I found This which is cleanest i've found. I have confirmed the new OOTB options are not suited. This is just showig switching out form membership to use the AD Membership instead. You can then just clear out all the ApplicationUser stuff.</p>


问:
For instance methods, would always returning self or this, instead of using a void return type, be a clean coding style?
I just came across this article, and in particular, this answer.  Essentially they're talking about returning self from instance methods to allow for method chaining.  That being said, one of the first thoughts that came to mind was, Why not always take instance methods with void return types and make them return this or self instead?  The next thought, which came to mind immediately, was, There's probably a reason this isn't more common.  So what could be the harm in it?

It seems like there honestly wouldn't be any.  The reason is that nothing about the mere existence of a return value implies or even seems to imply the need to use that return value.  If the method is a specialized getter or file reader or something, that's one thing, but if people aren't looking to use the return value, they naturally won't pay one any attention.  Furthermore it shouldn't be too confusing, because return this; is pretty trivial; at most, somebody would probably think it's irrelevant.  It certainly seems like it wouldn't hurt anything, and it's generally better to have too much than too little.

答:
In general, methods returning void should be uncommon. Why? It means that for the method to do anything meaningful, it needs to mutate the class or have some other side effect. Mutations and side effects generally cause trouble with concurrency, testing, and reasoning about the correctness of your program.

Worse, the trend in modern object oriented programming is to favor immutable objects more and more. What does the function signature look for methods that do some operation and then return a new form of the object (think DateTime.AddHours)? That's right, the same as some self returning mutating function.

And in general, ignoring return values is a code smell, often obscuring error handling or other errors.

In short - it can lead to clean code if that is the idiom in your language/environment, but is a bad idea in general, going against the trends of best practices.


问:
object model and data model
I have heard/read mixed things on whether to start with an object model or a data model. And more people say to starting with an object model as it will ease your data modelling.

My question is, Shouldn't an object model always drive the design of data model? Why and When would a data model design be different than an object model?

If we have a good object model, shouldn't the classes we come up with translate into tables? And class associations as table relationships?

答:
The question is not very rich in practical facts. And practical facts would definitely drive which model might be better to begin with. With that said:

if you start with a relational model and derive the object model, your object model will be conceptually more divergent (and thus almost certainly less useful) from what it is intended to represent than if you began with the object model

if you start with the object model(s) then you will always be able to physically model relationally. however, if your object model is complex, you may need some moderate to expert relational modeling skills to make the "translation", something many (most?) object oriented developers are deficient in

Title: object model and data model


问:
Purposely raising exceptions to use catch
For a typical if...else wrapped with exception handling, is something like the following example a recommended practice to avoid code duplication?

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        throw new Exception();
    }
catch(Exception ex)
{
    return null;
}
</code>```

instead of...

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        return null;
    }
}
catch(Exception ex)
{
    return null;
}
</code>```

I know there is a slight performance hit, but I'm wondering if this is considered to be an acceptable practice. I currently do it the second method - especially in cases where I need to handle specific exceptions differently - but I was wondering if the first method is appropriate for simple cases.

答:
Using exception handling for flow control is discouraged by Microsoft.

And a round table on the topic is available.

That being said, C# supports doing so, and I suppose it depends on the condition encountered whether an exception is the most appropriate response.

OwnerDisplayName: grovesNL


答:
The performance hit is most probably negligible, as explained in this answer.

So let's go with the idea that performance isn't an issue. You're throwing System.Exception, just to move execution into the catch clause. Throwing a BadControlFlowThatShouldBeRewrittenException would probably be overkill though.

Let's break this down. We have:

Method GetDataFromServer (method names should be PascalCase in C#), which can possibly throw an exception, or return a bool.

If result was true, run ProcessData.

Return null otherwise.

Looks like the method where this code is written, is simply doing too many things. GetDataFromServer returning a bool looks like a design flaw, I'd be expecting that method to return the data it's getting from the server, some IEnumerable<SomeType> that would contain 0 or more items - i.e. happy path returns n items where n > 0, not-so-happy path returns 0 items, and unhappy path blows up with an unhandled exception, whatever that is.

That changes what the method looks like, quite a lot - again it's hard to tell whether this makes sense, because the original post only has one exit point (and thus wouldn't compile, as not all code paths return a value), so this is only a wild guess:

```<code>try
{
    var result = GetDataFromServer();
    return ProcessData(result);
}
catch
{
    return null;
}
</code>```

Here you'd look at ProcessData and see that it's iterating the result, and returns null if there's no item in the IEnumerable.

Now why is the method returning null? Server was down? Is there a bug in the query? The connection string is using the wrong credentials? Whenever GetDataFromServer blows up with an exception you're not expecting, you're swallowing it, shoving it under the carpet and returning a null value. I'd recommend catching specific exceptions in this case, and log everything else; debugging will be much easier that way.

With a general catch clause that doesn't capture the exception, it gets pretty hard to diagnose anything. I'd minimally do this instead:

```<code>catch(Exception e)
{
    return null;
}
</code>```

Now you can at least break and inspect e if things go wrong.

TL;DR: No, throwing and catching exceptions for flow control isn't a good idea.

Title: Purposely raising exceptions to use catch

Body:
For a typical if...else wrapped with exception handling, is something like the following example a recommended practice to avoid code duplication?

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        throw new Exception();
    }
catch(Exception ex)
{
    return null;
}
</code>```

instead of...

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        return null;
    }
}
catch(Exception ex)
{
    return null;
}
</code>```

I know there is a slight performance hit, but I'm wondering if this is considered to be an acceptable practice. I currently do it the second method - especially in cases where I need to handle specific exceptions differently - but I was wondering if the first method is appropriate for simple cases.

Body:
The performance hit is most probably negligible, as explained in this answer.

So let's go with the idea that performance isn't an issue. You're throwing System.Exception, just to move execution into the catch clause. Throwing a BadControlFlowThatShouldBeRewrittenException would probably be overkill though.

Let's break this down. We have:

Method GetDataFromServer (method names should be PascalCase in C#), which can possibly throw an exception, or return a bool.

If result was true, run ProcessData.

Return null otherwise.

Looks like the method where this code is written, is simply doing too many things. GetDataFromServer returning a bool looks like a design flaw, I'd be expecting that method to return the data it's getting from the server, some IEnumerable<SomeType> that would contain 0 or more items - i.e. happy path returns n items where n > 0, not-so-happy path returns 0 items, and unhappy path blows up with an unhandled exception, whatever that is.

That changes what the method looks like, quite a lot - again it's hard to tell whether this makes sense, because the original post only has one exit point (and thus wouldn't compile, as not all code paths return a value), so this is only a wild guess:

try
{
    var result = GetDataFromServer();
    return ProcessData(result);
}
catch
{
    return null;
}

Here you'd look at ProcessData and see that it's iterating the result, and returns null if there's no item in the IEnumerable.

Now why is the method returning null? Server was down? Is there a bug in the query? The connection string is using the wrong credentials? Whenever GetDataFromServer blows up with an exception you're not expecting, you're swallowing it, shoving it under the carpet and returning a null value. I'd recommend catching specific exceptions in this case, and log everything else; debugging will be much easier that way.

With a general catch clause that doesn't capture the exception, it gets pretty hard to diagnose anything. I'd minimally do this instead:

catch(Exception e)
{
    return null;
}

Now you can at least break and inspect e if things go wrong.

TL;DR: No, throwing and catching exceptions for flow control isn't a good idea.

OwnerDisplayName: retailcoder


答:
in your first answer there is a performance hit that doesn't need to be there.

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        throw new Exception();
    }
catch(Exception ex)
{
    return null;
}
</code>```

when you exit the if statement to enter into the Catch statement when you don't have to makes the code switch directions, so to say.

if you want to return null;  do it in the else statement not in a catch that is caught after being thrown from the else statement.

Probably doesn't apply to your Real code, but for the Generic code that you gave it does apply.

Standards say you shouldn't do this.

Standards say you should do it like this, (again based on Generic Code Given in OP)

```<code>if (GetDataFromServer())
{
    return ProcessData();
}
else
{
    Return null
}
</code>```

and since you don't have any specific exceptions that you are catching you shouldn't even have a try catch here.

you want to see Exceptions when they occur so that you can fix the issue that creates the exception.

Body:
in your first answer there is a performance hit that doesn't need to be there.

try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        throw new Exception();
    }
catch(Exception ex)
{
    return null;
}

when you exit the if statement to enter into the Catch statement when you don't have to makes the code switch directions, so to say.

if you want to return null;  do it in the else statement not in a catch that is caught after being thrown from the else statement.

Probably doesn't apply to your Real code, but for the Generic code that you gave it does apply.

Standards say you shouldn't do this.

Standards say you should do it like this, (again based on Generic Code Given in OP)

if (GetDataFromServer())
{
    return ProcessData();
}
else
{
    Return null
}

and since you don't have any specific exceptions that you are catching you shouldn't even have a try catch here.

you want to see Exceptions when they occur so that you can fix the issue that creates the exception.

OwnerDisplayName: Malachi


问:
Responding to app feature requests I'm not going to implement
I'm a new app developer and after like 20 downloads of my app (free and ad-free) I already got two feature requests, and I'm not going to implement either.

Should I respond to these feature requests and if so, how? I'd prefer not responding at all because I'd rather spend the time to work on my app, but being a new developer, a couple of poor ratings in the app store could hurt my app.

答:
I think the other answers are on the right path in encouraging you to correspond with your users.

one feature request turned into 7..

Based on this comment, you're not giving users enough feedback on the types of features you are open to. Maybe they want you to expand the capabilities/feature set but you're more concerned with performance and usability of existing features? Declining a single feature isn't enough to guide users. They'll keep using trial and error and in your pen-pal's case, the shotgun approach.

The goal is to encourage feedback and give it some direction.