问:
Exceptions vs ErrorCodes when working with devices
Out team is at the cusp of a new project.
One of the components at the boundary of the system is the component which interacts with a printer through an external COM component (referenced as a usual dll).

The COM component returns integer codes if there were an error whilst command execution.
Lets consider a concrete code.

```<code>  public class OperationException:Exception {
    public int ErrorCode { get; private set; }
    public string ErrorDescription { get; private set; }

    public OperationException(int errorCode, string errorDescription) {
        ErrorCode = errorCode;
        ErrorDescription = errorDescription;
    }
}

//The exception throwing way
public class Provider1:IFrProvider {
    private readonly IDrvFR48 driver;

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            throw new OperationException(resultCode, driver.ErrorDescription);
        }
        return driver.SerialNumber;
    }
}

//The way of out parameters returning.
public class Provider2 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public string GetSerialNumber(out Result result) {
        //must read status before get SerialNumber
        int resultCode = driver.ReadEcrStatus();
        if (resultCode != 0) {
            result = new Result(resultCode, driver.ErrorDescription);
            return null;
        }
        result = new Result(0, null);
        return driver.SerialNumber;
    }
}

//The way of LastResult property setting.
public class Provider3 : IFrProvider
{
    private readonly IDrvFR48 driver;

    public Result LastResult {
        get {
            return new Result(driver.ErrorCode, driver.ErrorDescription);
        }
    }

    public string GetSerialNumber() {
        //must read status before get SerialNumber
        if (driver.GetECRStatus() == 0)
            return driver.SerialNumber;
        return null;
    }
}

public class Result {
    public int ResultCode { get; private set; }
    public string Description { get; private set; }

    public Result(int resultCode, string description) {
        ResultCode = resultCode;
        Description = description;
    }
}

public class Caller {
    public void CallProvider1() {
        var provider = new Provider1();
        try {
            string serialNumber = provider.GetSerialNumber();
            //success flow
        }
        catch (OperationException e) {
            if (e.ErrorCode == 123) {
                //handling logic
            }
        }
    }

    public void CallProvider2() {
        var provider = new Provider2();

        Result result;
        string serialNumber = provider.GetSerialNumber(out result);
        if (result.ResultCode == 123) {
            //error handling
        }
        //success flow
    }

    public void CallProvider3()
    {
        var provider = new Provider3();

        string serialNumber = provider.GetSerialNumber();
        if (provider.LastResult.ResultCode == 123) {
            //handling
        }
        //success flow
    }
}
</code>```

So we have three ways of error handling. The most specific thing in all this stuff is that each operation can fail, because it depends on a device.

Our team think of using out parameters, because of unhandled exceptions propagation fear. The other reason, connected with the fear, is that we will have to cover all calls by try\catch blocks to stop to be afraid, but such a code will be pretty ugly.

What pros and cons do you see and what could you advice?

答:
When designing an API for operations which may fail because of foreseeable reasons, but at unforeseeable times, one should generally allow a means by which callers can indicate whether they are expecting to cope with the semi-foreseeable failures.  If the only methods which are available return with error codes rather than exceptions, then every call site will be required to test the return value, even if the only thing it can do with an error code is throw an exception.  If the only methods which are available throw exceptions for all failures, even ones a caller might be expecting, then every caller that would be prepared to handle a failure will have to use a try/catch for that purpose.

A common means for exposing methods whose callers may or may not expect failures is to have pairs of methods that fnorble named, e.g., TryFnorble and Fnorble.  Suppose Thing1a and Thing1b have both styles of method, while Thing2a only has the first and Thing2b only has the second.  Code which is prepared to handle a problem with the first thing but not the second could be written as:

```<code>Thing1a.Fnorble();
if (Thing1b.Fnorble())
  Thing1bIsReady = true;
else
  Thing1bIsReady = false;
</code>```

By contrast, if the code was using Thing2a/Thing2b, it would need to be written as:

```<code>if (!Thing2a.Fnorble())
  throw new FnorbleFailureException(...);
try
{
   Thing2b.Fnorble();
   Thing2bIsReady = true;
}
catch (Ex as FnorbleFailureException)
{
   Thing2bIsReady = False;
}
</code>```

Much less nice.

[Note: I use an if/else and explcitly set/clear the Thing1bIsReady flag, rather than simply assigning the return value directly to the flag, because even though the return type and flag are both bool, I would regard them as having semantically different meanings.  I would consider the fact that having the method return true once would cause the flag to be set immediately, and having it return false once would cause the flag to be cleared immediately as an implementation detail.

Body:
When designing an API for operations which may fail because of foreseeable reasons, but at unforeseeable times, one should generally allow a means by which callers can indicate whether they are expecting to cope with the semi-foreseeable failures.  If the only methods which are available return with error codes rather than exceptions, then every call site will be required to test the return value, even if the only thing it can do with an error code is throw an exception.  If the only methods which are available throw exceptions for all failures, even ones a caller might be expecting, then every caller that would be prepared to handle a failure will have to use a try/catch for that purpose.

A common means for exposing methods whose callers may or may not expect failures is to have pairs of methods that fnorble named, e.g., TryFnorble and Fnorble.  Suppose Thing1a and Thing1b have both styles of method, while Thing2a only has the first and Thing2b only has the second.  Code which is prepared to handle a problem with the first thing but not the second could be written as:

Thing1a.Fnorble();
if (Thing1b.Fnorble())
  Thing1bIsReady = true;
else
  Thing1bIsReady = false;

By contrast, if the code was using Thing2a/Thing2b, it would need to be written as:

if (!Thing2a.Fnorble())
  throw new FnorbleFailureException(...);
try
{
   Thing2b.Fnorble();
   Thing2bIsReady = true;
}
catch (Ex as FnorbleFailureException)
{
   Thing2bIsReady = False;
}

Much less nice.

[Note: I use an if/else and explcitly set/clear the Thing1bIsReady flag, rather than simply assigning the return value directly to the flag, because even though the return type and flag are both bool, I would regard them as having semantically different meanings.  I would consider the fact that having the method return true once would cause the flag to be set immediately, and having it return false once would cause the flag to be cleared immediately as an implementation detail.


问:
What's the proper way of dealing with a global file path?
I don't have compilable code, because the code in question depends on a large function that's irrelevant to the question, but say I have the following scenario:

```<code>savePath = "C:\\..."

changePath1, changePath2 :: String -> String

changePath1 passedPath =
    'Do something with passedPath'

changePath2 =
    'Do something with savePath'

let newPath1 = changePath1 savePath in ...
let newPath2 = changePath2 in ...
</code>```

Is it more proper to set up functions like changePath1 (where the global path is passed in), or changePath2 (where it just internally uses the global path)
If the functions had a chance of processing more then 1 path, obviously I'd use changePath1, but in my current program, there is only 1 path to deal with, so it seems simpler to just have all the functions internally know the global path instead of constantly passing it in.

Thank you

答:
In Haskell in particular, you can have your cake and eat it, too!

```<code>changePath2 :: Reader FilePath FilePath
changePath2 = do savePath <- ask
                 -- do stuff with 'savePath'

changePath1 :: FilePath
changePath1 = runReader changePath2 "C:\\..."
</code>```

For this trivial example, of course, you could just as easily use an ordinary function rather than Reader, but using Reader scales up to much more complicated "static dependecy injection"-style things that this example only gives a glimpse of.

ContentLicense: CC BY-SA 3.0

Body:
In Haskell in particular, you can have your cake and eat it, too!

changePath2 :: Reader FilePath FilePath
changePath2 = do savePath <- ask
                 -- do stuff with 'savePath'

changePath1 :: FilePath
changePath1 = runReader changePath2 "C:\\..."

For this trivial example, of course, you could just as easily use an ordinary function rather than Reader, but using Reader scales up to much more complicated "static dependecy injection"-style things that this example only gives a glimpse of.


问:
Understanding exceptional cases
I've been studying the use of exceptions in various php projects (such as Doctrine and Zend Framework). Exceptions seem to be thrown when unordinary input/state occurs. A perfect example is Doctrine throwing an exception when you try to use a invalid query string.

I think the creators of the doctrine api understood that first, you can't query data by using an invalid DQL statement, and a developer should immediately be warned that an error has occurred, rather then letting execution continue with the possibility of an error code going un-checked. I also bet that this simplifies reading the code. I can't think of a situation where you would want to use an invalid DQL statement, except unit testing. Since this is true, it's better to avoid plaguing a bunch of code with null/error checks and use exceptions.

I've read in books that exceptions shouldn't be thrown when validating dating user input. I've seen examples where of where the guideline is broken. One example is the Zend framework. If supplying an invalid controller or action name, an exception is thrown. Unlike doctrine, the user has more direct control over this sort of input. I know you can configure an error controller and set up a 404 message or what have you, but I'm curious why they have used an exception in this scenario? I guess you can argue the Zend Framework does not know how to continue processing the request.

One last example Is I wrote a function to return some html based on a given resource type. This resource type is hard-coded and sent when a user interacts with a web site (such as clicking a button to display the form to input data). I don't expect users to be mucking around with the request type. Under normal operating conditions, the resource type should be valid. To clean up some logic, I was going to throw an  exception if a particular form wasn't found. This is mainly to find the correct form associated with a resource type so proper validation can occur. Does this sound like a valid use case for an exception? Right now it's pretty trivial, but I do plan to implement a restful consumer and re-using a function to map resources to their validation services would be very useful. I can then catch the exception and based on the consumer, return an error message suitable for the request type...

答: One should return error indications for things an immediate caller is prepared to handle, and exceptions for things an immediate caller is not prepared to handle.  If conditions may arise while performing an action that some immediate callers will be prepared to handle but other immediate callers will not, it may be helpful to have a method which will return an error indication in such cases (for use by callers that are expecting the condition) and another method which will throw an exception (for callers which would be unable to do anything in the error case except throw an exception themselves).</p>

Title: Understanding exceptional cases


问:
industry averages for time spent on maintenance
A manager recently announced that were were spending far too much time fixing bugs. I guess he thinks we should write perfect code all the time (whilst still hitting those impossible deadlines of course!) and it made me wonder what the industry average of time spent bug fixing v writing new code was.

So does anyone have any metrics on time spent bug fixing against new code development? Or is there any empirical analysis of bug fixing time for the industry as a whole? Is 50% spent bug fixing too much, or about right? How about 20% or 33%?

I'm happy to accept anecdotal evidence from personal experience as that would form part of some statistics here that I could compare our performance against.

答:
if your using a good ticket tracker (Such as Jira from Atlasian) and you've spent time entering all the different categories, user stories, urgency levels correctly and with the agreement of your team mates, then actually calculating these metrics (and more) are amazingly easy.

On a previous project, we used Jira to manage our bug/task/todo lists, and in the end it actually showed us that the biggest cause of delays and problems turned out to be inefficient management practices.

Strangely enough, when that information came out, we where suddenly told that we would no longer be using Jira, and that a new product would be brought in to replace it.

In the mean time, all requests for data to be passed through Jira had to be sent to the management team, and we had our direct access removed.

What wasn't noticed was that as part of the stats calculation, the dev team had Jira poking data to a web hook, and this web hook was used to pass data to an end point on some internal servers, where we had code that created these reports automatically.

We started monitoring the web hook, and found that even though we where told that Jira was no longer used, it remained very much alive for a considerable amount of time longer (6+ months to be exact) and the wholesale abuse by upper management was just plain rampant with incorrect use.

Of course, it doesn't have to be something as complex as Jira.

If you want a low yield solution, you could use a google-docs spread sheet, and the GDocs notification API, to track tasks/tickets/bugs/feature requests etc.

GDocs itself can now issue web-hooks and all sorts of things.

Couple that with Git and/or Github and some hooks that trigger when code is committed to your repository, and you've got a reasonably efficient home brew system, that can record a surprising amount of data.

In general however, out of 100% of a products natural lifetime, the split between greenfield dev and maintenance is generally 20/80, most of the cost in the ALM (Application Lifetime Management) cycle is taken up on maintenance and support costs.

There's no such thing as spending too much time fixing bugs, beacuse it's simply not possible to write bug-free code.

Good testing and continuous integration policies will reduce the deficiet , but you'll never completely eradicate it.

Anyone who believes otherwise (IMHO) doesn't have enough knowledge to make an acurate judgment, or is blind (The more usual case) to just how difficult it actually is to write software.

If your manager is up for it, and some of them are, then you might want to suggest that he shadows you for a day, so he can see exactly what you do and how you do it.

Iv'e worked in a few companies where this kind of work was actively encouraged, with upper level staff shadowing lower level staff, and vice-versa, it can be a really, really good learning experience for both involved parties.


问:
Choosing between the view and the controller for my code
I'm aware there are a lot of topics about MVC design but it's hard to find good explanations: what I should do, what are the consequences of the different possibilities...

So I'm working on an ASP .NET MVC application with a HTML/Javascript front-end. Currently there is a view which allows the end-user to edit some objects like the others users. The form is automatically generated based on some meta-data. But these objects are rather complex, with many system properties and need to be edited by non-expert users. As we don't want to spend much time on the view, we decided to just hide all the input fields except the most simple ones like first name, last name, phone...

My question is, does this filtering should be done in the controller or in the view ? Should I Ignore the most complex input fields in the view or only returns the needed fields from the controller ?

Also my controller returns the data from the model without any post-processing. So it is done in the view. I could do it in the controller in order to save some ajax-calls and a little bandwith but I don't know if I should adapt the controller to the view or the view to the controller.

答:
EEK... nooo my friend, hiding controls is the last thing you should do.

If your using MVC, and I assume (Judging by your description) the Model Binding syntax, where your forms are generated using Razor and the HTML Helpers, then your already half way towards letting MVC do all the work for you.

There are 2 main strategies when it comes to ASP.NET MVC.

Strategy Number 1 - Use ONLY the flattened models and properties you need to use.

In this scenario, you need to be using a well architecture, well tiered application solution, with different very separate levels of operation for things like presentation, Business rules, Data and possibly others too.

In your presentation layer, you model your objects to contain ONLY the properties you need to display, everything else such as system properties to control things you provide using property accessor's, functions/methods and a well though out abstraction of functionality throughout the entire object graph.

Your business layer, should take full objects containing everything from the data layer, and then flatten them, or combine them into single simple to manage objects, that contain only the information needed to do their job.

Doing things this way, requires a lot of planning up front, lots of fore thought, and leaves little or no room for scope creep or last minute changes, and if used fully is more suited to greenfield projects where you have total control from the beginning.

Strategy Number 2 - Use the ASP.NET Data annotation facilities

The ASP.NET MVC Model binder provides a fantastic set of attributes to control every aspect of your data model.

You can specify things like '[Required]', '[Min]', '[Datatype]' and much more.

Attributes are applied in the following fasion:

```<code>public myclass
{
  [Required]
  public string name { get; set; }
}
</code>```

and are examined and acted on by every level of the framework.

In the case of my example above, if you used the razor form generators, you would get a form that specifies an input box for name, and if you tried to submit that form with no name supplied, the framework will tell you in your controller code that something was wrong, allowing you to pass the model straight back to the view without doing anything.

In most cases, it will also change the formatting and CSS for you to show that there is an error.

There's more than this though.

There are attributes, to tell a field that it's a hidden input, of a read only input, which means that when the model is rendered using something like '@beginform' these fields will automatically be removed from the display for you, again without you having to write a single line of code, or modify a html tag, css rule or attribute in the view page.

If you combine the 2...

Then things get even better, you have full fat models down in the code where it matters and where they are needed, and light weight models only containing whats needed for display in the presentation.

You can even go one step further, and using something like Angular, Knockout or Backbone, you can have your controllers return only JSON, then you can do your entire UI in an MVVM fashion.

This way you feed javascript object models that act like the code behind your view, and have your UI components update automatically based on these view models.

The beauty of using the JSON approach, is you can add as many different types of UI to your solution as you want.

Web browser for the desktop, mobile app for the phone, hybrid app for tablets, and plain old desktop standalone apps for the back room staff feeding data into the system, all working off a common set of JSON endpoints.

Here are a couple of links that provide some further reading as to what data attributes are available, and what it's possible to do with them.

MVC Tutorial part 6 by Jon Galloway

MSDN Documentation

Jon Galloway's entire series is well worth reading, Jon is a fellow pluralsight author and Iv'e had the pleasure of reviewing some of the material he's created for them, it's all exceptional quality and very informative.

Body:
EEK... nooo my friend, hiding controls is the last thing you should do.

If your using MVC, and I assume (Judging by your description) the Model Binding syntax, where your forms are generated using Razor and the HTML Helpers, then your already half way towards letting MVC do all the work for you.

There are 2 main strategies when it comes to ASP.NET MVC.

Strategy Number 1 - Use ONLY the flattened models and properties you need to use.

In this scenario, you need to be using a well architecture, well tiered application solution, with different very separate levels of operation for things like presentation, Business rules, Data and possibly others too.

In your presentation layer, you model your objects to contain ONLY the properties you need to display, everything else such as system properties to control things you provide using property accessor's, functions/methods and a well though out abstraction of functionality throughout the entire object graph.

Your business layer, should take full objects containing everything from the data layer, and then flatten them, or combine them into single simple to manage objects, that contain only the information needed to do their job.

Doing things this way, requires a lot of planning up front, lots of fore thought, and leaves little or no room for scope creep or last minute changes, and if used fully is more suited to greenfield projects where you have total control from the beginning.

Strategy Number 2 - Use the ASP.NET Data annotation facilities

The ASP.NET MVC Model binder provides a fantastic set of attributes to control every aspect of your data model.

You can specify things like '[Required]', '[Min]', '[Datatype]' and much more.

Attributes are applied in the following fasion:

public myclass
{
  [Required]
  public string name { get; set; }
}

and are examined and acted on by every level of the framework.

In the case of my example above, if you used the razor form generators, you would get a form that specifies an input box for name, and if you tried to submit that form with no name supplied, the framework will tell you in your controller code that something was wrong, allowing you to pass the model straight back to the view without doing anything.

In most cases, it will also change the formatting and CSS for you to show that there is an error.

There's more than this though.

There are attributes, to tell a field that it's a hidden input, of a read only input, which means that when the model is rendered using something like '@beginform' these fields will automatically be removed from the display for you, again without you having to write a single line of code, or modify a html tag, css rule or attribute in the view page.

If you combine the 2...

Then things get even better, you have full fat models down in the code where it matters and where they are needed, and light weight models only containing whats needed for display in the presentation.

You can even go one step further, and using something like Angular, Knockout or Backbone, you can have your controllers return only JSON, then you can do your entire UI in an MVVM fashion.

This way you feed javascript object models that act like the code behind your view, and have your UI components update automatically based on these view models.

The beauty of using the JSON approach, is you can add as many different types of UI to your solution as you want.

Web browser for the desktop, mobile app for the phone, hybrid app for tablets, and plain old desktop standalone apps for the back room staff feeding data into the system, all working off a common set of JSON endpoints.

Here are a couple of links that provide some further reading as to what data attributes are available, and what it's possible to do with them.

MVC Tutorial part 6 by Jon Galloway

MSDN Documentation

Jon Galloway's entire series is well worth reading, Jon is a fellow pluralsight author and Iv'e had the pleasure of reviewing some of the material he's created for them, it's all exceptional quality and very informative.


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答: The only time I can recall seeing string reversal being used was a function I saw way back that used it while parsing file names, to ensure that the '.' it found in the file name was in fact the last dot that seperated the file name from extension.  ie, parsing a file name like data.2010.12.08.dat, you'd reverse the string, find the first dot, subtract that position from the end of the original string, and take the substring.  I'm not saying thats the optimal way to do it, but thats what it did.  It may have been in powerbuilder, where such wierd uses of functions were common to workaround various non-obvious problems.

ContentLicense: CC BY-SA 2.5

Title: What do you use string reversal for?


问:
What does it mean for a sorting algorithm to be "stable"?
In reading about various sorting algorithms I've seen it mentioned that some are "stable" and some are not. What does that mean, and what tradeoffs are involved on that basis when selecting an algorithm?</p>

答:
A stable sort is one which preserves the original order of the input set, where the comparison algorithm does not distinguish between two or more items.

Consider a sorting algorithm that sorts cards by rank, but not by suit.  The stable sort will guarantee that the original order of cards having the same rank is preserved; the unstable sort will not.


答:
Stable algorithms preserve the relative order of elements.

So a stable sorting algorithm will retain the relative order of values which compare as equal.

Consider a sorting algorithm where we sort a collection of 2d points based on their X dimension.

Collection to be sorted: {(6, 3), (5, 5), (6, 1), (1, 3)}

Stable Sorted: {(1, 3), (5, 5), (6, 3), (6, 1)}

Regular Sorted: Either {(1, 3), (5, 5), (6, 3), (6, 1)}, or {(1, 3), (5, 5), (6, 1), (6, 3)}

As for the tradeoff... well, stable sorting is less efficient, but sometimes you need it.

For example when a user clicks the a column header to sort values in a UI, it's reasonable to expect his previous sorting order to be used in the case of equal values.

Title: What does it mean for a sorting algorithm to be "stable"?

Body: In reading about various sorting algorithms I've seen it mentioned that some are "stable" and some are not. What does that mean, and what tradeoffs are involved on that basis when selecting an algorithm?</p>


问:
Is this a good practice or not?
I have a colleague who has come up with a way of 'genericizing' information from a database so that all his web application's drop-down lists can share the same object in his MVC.NET C# code and Views, which can contain different data depending on what tables it is being used against.

We work for a government agency, and we have facilities divided up into areas called "Regions", which contain further subdivided areas called VISNs, which each contain "Sites" or "Facilities". My colleague has developed a very complex security scheme whereby people can be granted access to data based on their permission level which can be assigned by Region, VISN, Site, or any mixture of the three. It's a nice scheme and very clever. However, he has stored procedures that return lists of Regions, VISNs, and Sites based on a person's User Id, and he is returning "generic" values like TextFieldID, TextField, and TextParentID. My first problem with this, is that looking at this data coming out of the database, I would not know what the data is. I feel that fields coming from a query or stored procedure should be descriptive of the data they are delivering. What does everyone else think? The deeper issue for me however is that he is taking some of the data, concatenating it in his stored procedure like this

SELECT DISTINCT
    t.VisnID,
    NULL,
    t.StationID,
    'V' + CAST(t.VisnID as varchar) + ': ' + t.Station3N + ': ' + t.StationName,
    t.Inactive
FROM Stations t
```

<p>and sending it back in a "TextField" property, instead of sending back the discrete data separately (<code>Station3N</code>, <code>StationName</code>) and concatenating it in the View, which would allow for different concatenation depending on what device what accessing the application (perhaps mobile and desktop). His justification is that he can send all his various drop down data and capture them all, regardless of content, in the same C# object named "LookupValue." </p>

```public partial class LookupValue : IEquatable<LookupValue>
{
    public LookupValue(string textFieldId, string textField, bool inactive)
    {
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    public LookupValue(string textParentId, string textSelfParentId, string textFieldId, string textField, bool inactive)
    {
        TextParentID = textParentId;
        TextSelfParentID = textSelfParentId;
        TextFieldID = textFieldId;
        TextField = textField;
        Inactive = inactive;
    }

    ///
    /// Returns a custom string identifier if the Inactive property is true.
    ///
    public string GetInactiveString()
    {
        string value = "";
        if (Inactive)
        {
            value = "[I]";
        }

        return value;
    }

    ///
    /// Returns a custom text label that concatenates the TextField property with the custom string identifier of the Inactive property.
    ///
    public string GetDisplayNameWithInactiveString
    {
        get { return TextField + " " + GetInactiveString(); }
    }

    public bool Equals(LookupValue other)
    {
        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal.
        return TextFieldID.Equals(other.TextFieldID) && TextField.Equals(other.TextField);
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public override int GetHashCode()
    {
        //Get hash code for the TextFieldID field if it is not null.
        int hashTextFieldId = TextFieldID == null ? 0 : TextFieldID.GetHashCode();

        //Get hash code for the Code field.
        int hashTextField = TextField.GetHashCode();

        //Calculate the hash code for the product.
        return hashTextFieldId ^ hashTextField;
    }
}
```

He believes the re-usability of this object is worth the violation of Separation of Concerns and possible future difficulties in handling more than one display variation for a drop-down. I should point out that this object is contained in his Data project namespace (our projects are separated into Data, Web, Services, etc.) instead of the Web project namespace and he also returns this object to the Web layer via his Repository queries which call the stored procedures that I described earlier,  which is gross violation of Separation of Concerns in my opinion.

I am just looking for some confirmation from other programmers that this is in fact a bad practice, and also looking for ideas I can present him on better ways to do what he is attempting. I have my own ideas, but again I'm just looking for other's ideas so I have more options to present to him.

--Edit -- I forgot to mention that we are using Entity Framework as an ORM, and his Repository classes in his DAL are dumping the data from the stored procs into this LookupValue object.

答:
a way of 'genericizing' information from a database so that all his web application's drop-down lists can share the same object in his MVC.NET C# code and Views, which can contain different data depending on what tables it is being used against.

So, we take a DB schema that generally maps to the problem space at hand, and a user UI that generally maps to the problem space at hand, then create a data transport mechanism between the two that generally maps to nothing. Hmmmm.

His justification is that he can send all his various drop down data and capture them all, regardless of content, in the same C# object named "LookupValue."

Where's the  design? We use a common class to fill dropdown lists - but it is a UI form/control with properties for customizing SQL, setting the list/collection itself, tying the list to the dropdown UI element, etc. Being a UI thing it gives common behavior as well.

LookupValue

The comments are banal, obvious, unnecessary

I see numerous violations of Open/CLosed principle in your future. My spidey sense says all those "this ID" and "that id" parameters, and that they are repetitive across constructors, is suspicious somehow. I wish I could be more specific.... I'd bet there are customized stored procedures for each constructor.

"Equateablitly" implementation is incomplete for the class. I'm not confident that the inherited, not over-ridden, Object.Equals() will return the same result as the IEquatable implementation. From MSDN: "If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object)"

Is there a LookupValue collection? If not, why implement IEquateable? Again, from MSDN: "The IEquatable interface is used by generic collection objects ... when testing for equality. ...  It should be implemented for any object that might be stored in a generic collection. "

I forgot to mention that we are using Entity Framework as an ORM, and his Repository classes in his DAL are dumping the data from the stored procs into this LookupValue object.

So he is willfully subverting the application architecture. Does he have approval for that? Are y'all purposefully getting away from the ORM? Hmmmm.

How badly does this blow your inherent data binding? How much extra code do you write for that?

The deeper issue for me however is that he is taking some of the data, concatenating it in his stored procedure like this ...

So much for arguing re-usability. You are right to call it "a deeper issue."

I recall having to write whole new stored procedures because of this. And these were virtually identical save for that special customization. One of these procedures "decided" that all blank/null numbers were zero - sounds reasonable, clearly a DB only issue. That did not survive the next requirements cycle!

How is that concatenation parsed on the receiving end? I bet it's not even a class. IMHO, any string that has imbedded coding/meaning should be a class unto itself so that the meaning is properly expressed and encapsulated.

My colleague has developed a very complex security scheme whereby people can be granted access to data based on their permission level which can be assigned by Region, VISN, Site, or any mixture of the three. It's a nice scheme and very clever. However, he has stored procedures that return lists of Regions, VISNs, and Sites based on a person's User Id

So he's willfully subverting the application architecture. (see? I re-used that sentence!).  I mean, I assume y'all are taking advantage of the database's built-in security and access features. So now you have to keep these in synch!

In Conclusion

the re-usability of this object is worth the violation of Separation of Concerns and ...

Re-useability is not a principle - it is a consequence - of good object oriented design and coding.

He has woven a tapestry of un-maintainability and anti-design around a single class that is "re-usable." This is clearly not a balanced application of OO principles and guidelines.

Why would someone perpetrate such obscureata? Psycodeologists say they get a sense of superiority from creating something others do not understand.  You may disprove this simply by showing me the documentation. What, no documentation? Hmmm.

Title: Is this a good practice or not?


问:
When to Use workflow engines?
I've worked in past on some of the workflow engines as programmer but never had a clarity on why we chose the work-flow engines in first place. And as programmer I know that there are at least 100 ways to do anything when you are writing code but only few of the ways are the best!

I still don't understand which use cases are best solved by workflow engines (or rather their concept) than designing a good DI enabled application. I'm looking for any general characteristics of domain-neutral use cases, where work-flow engines are one of the the best options.

So my question is: What are general characteristics of a requirement which can be taken as a signal for opting for a good workflow engine and coding around it?

答:
I have a couple of guidelines I use for suggesting work-flow engines.

1) When the business analysts have no coding background but can draw diagrams.

Modern work flow engines use business process modelling notation, or the less capable versions available in SharePoint and similar systems. These allow technically competent yet coding-challenged members of the team to design and develop many work flows.

2) When you need to monitor the progress of work, perform escalations, flip back and forth between computer-controlled processes and human-controlled processes.

Monitoring and self-reference are hallmarks of modern work flow engines.

Title: When to Use workflow engines?


问:
Beginning Design as a Programmer
I'm just starting to get in to web development. I'm learning Rails at the moment. I have lots of experience with various programming languages.

I've been searching for books to help me get started; I want to focus on writing clean, standards-compliant HTML and CSS.

Does anyone know of any modern, standards-based resources I can use, particularly books?

Thanks!

答:
If your focus is clean HTML and CSS, you probably can't do any better than

CSS Mastery

It's written by some of the most influential CSS experts from the last several years.

Title: Beginning Design as a Programmer


问:
Finding the time complexity of the following program that uses recursion
I need to find the time complexity in terms of Big Oh notation for the following program which computes the factorial of a given number: The program goes like this:

```<code>public int fact(int n){

  if (n <=1)
    return 1;
  else
  return n * fact (n-1);
}
</code>```

I know that the above program uses recursion but how to derive the time complexity for the above program?

答:
I'm sorry for reviving an old question, but I think a mistake might be made here that is repeated over and over.

As far as I know, computational complexity is defined over the size of an efficient encoding of the input (n).

Given an input number m for for factorial, it is true that the algorithm requires m multiplications.
But this is not of linear order (i.e. the same order as the size of the encoded input), because an efficient encoding of a number m is of size n := log m

This means that the time complexity indeed IS exponential (m = 2^n multiplications) in the size of (an efficient encoding of) the input!

m multiplications are only linear in the input if you choose a unary encoding of the input, which is not an "efficient" choice.

On "Efficient encodings"

Because user SSH asked, let me elaborate a bit on the notion of "efficient encodings".

The key to understanding it is understanding that the asymptotic complexity of an algorithm is defined in terms of "how fast the computational time grows, relative to how fast the input grows".

Usually the size of the input is intuitive: a list of n items has size n. But sometimes it can trip you up, as in the example that this thread focusses on. This is why the definition of computational complexity explicitly states "efficient encoding": to prevent you from making two possible mistakes:

1: forgetting you need to encode your input using a finite alphabet

In the factorial example, you might make the mistake of thinking your input size does not grow for bigger numbers, since you're always dealing with "one number". This is not valid, because it doesn't make sense to feed 'a number' to a turing machine (you need an infinite size alphabet). You need to encode the number using a finite alphabet and this representation of a number will grow when the number n get's bigger.

2: choosing an inefficient encoding

Because computational complexity is defined relative to the encoded input size, we could manipulate the complexity by choosing a very inefficent encoding.

For example: say we would encode a list of n items very inefficiently using n^2 tokens on the machine input tape; now suddenly all algorithms that use n^2 computational steps for lists of size n are linear in the encoded input size! That doesn't make sense ofcourse. So our encoding has to be efficient in order for our analysis to succeed.

Another example is listening to your intuition and thinking that the number 4 is twice as big in size as the number 2. This is not the case, because we can efficiently encode the number 2 using 2 bits and the number 4 using only 3 bits.

Potential pitfall: growth of vs. absolute encoded input size.

Just remember that we are not interested in the absolute size but in the growth rate of the encoded input: a list of 2*n integers is still twice the size of a list of n items.


问:
Single page app permissions represented through RESTful APIs
I'm trying to figure out the right way to handle permissions in a single page app that talks directly to several RESTful APIs, that implement HATEOAS.

As an example:

"As a user of my application I can view, start and pause jobs but not stop them."

The underlying rest API has the following resource:

```<code>/jobs/{id}
</code>```

Which accepts GET and PUT. The GET returns a job model and the PUT accepts a job model as a request body in the form:

```<code>{
 "_links" : {
     "self" : "/jobs/12345678"
 }
 "id" : 12345678,
 "description" : "foo job",
 "state" : "STOPPED"
}
</code>```

Accepted job states can be: dormant | running | paused | stopped.

The requirement says that on the UI I must have the buttons:

START, PAUSE, STOP

... and only display based on the logged in user's permissions.

From the API perspective everything works as the underlying logic on the server makes sure that the user cannot update the state to a STOPPED state when a request is made (a 401 is returned maybe).

What is the best way to inform the app / UI of the user's permissions, so it can hide any buttons that the user has no permission to action?

Should the API provide a list of permissions, maybe something like :

```<code>{
 "_links" : {
     "self" : "/permissions",
     "jobs" : "/jobs"
 }
 "permissions" : {
     "job" : ["UPDATE", "DELETE"],
     "job-updates" : ["START", "PAUSE"]
  }
}
</code>```

OR should the API change so that the permissions are reflected in the HATEOS links  maybe something like :

```<code>{
 "_links" : {
     "self" : "/jobs/12345678",
     "start" : "/jobs/12345678/state?to=RUNNING",
     "pause" : "/jobs/12345678/state?to=PAUSED",
 }
 "id" : 12345678,
 "description" : "foo job",
 "state" : "DORMANT"
}
</code>```

Or should it be done in a completely different way?

答:
Your second approach—including in the job model only links to actions the user is actually entitled to perform—is the one I would take.

It keeps the focus on the resource and the actions that can be performed on it, which makes it both relatively simple and a good fit conceptually for the REST architectural style.

It retains on the server all the logic surrounding users and permissions instead of spreading pieces of this across server and client.

It neatly mirrors your design on the user-facing side of things, where buttons the user shouldn't be allowed to click simply aren't presented.


问:
Coupling business logic with class definitions
Perhaps it is my scripting background, but my perspective is that the purpose of an object should be to contain data. Classes are necessary in that they provide templates and standard ways to classify and construct objects with particular data attributes. Standard protocol in object oriented design seems to be to include business logic in class definitions.

In a system that depends on state, I understand the motivation behind binding methods with the sole purpose of altering or retrieving the state of an object to the class definition. So let's exclude simple getters, setters, and constructors from the scope of the conversation.

The problems, as I see them, start when processes are bound to an object.

Consider a simple "string.equals()" method that accepts a string as a parameter, and returns a boolean indicating whether strings are equivalent. I think this simple method can cause enormous problems.

Let's say I have a LocationString class that inherited from String, where equals() is overridden as follows:

```<code>Boolean equals(LocationString otherLocation) {
    return extractCountry().equals(otherLocation.extractCountry());
}

String extractCountry(){
    return this.getCountry();
}
</code>```

Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different. Suddenly, the definition of equality changes for some of my classes. It becomes extremely painful to work out which equals definitions need to be changed. It becomes painful to work out whether other internal processes which called the equals method need to be changed. And eventually as the system expands, more hours are wasted searching through the code than analyzing it.

As such, to me it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives. Consider the following definition:

```<code>public static Boolean equals(Object a, Object b) {
    List locationClasses = Arrays.asList("LocationString")
    if (locationClasses.contains(a.getClass().getName()) && locationClasses.contains(b.getClass().getName()){
        return equals(a.extractCountry(), b.extractCountry());
    }
    else {
        return StringUtils.equals(a,b);
    }
}
</code>```

If all processes were defined externally, a change in process would not be all that difficult to correct and provided these more generic rules could be stored and categorized logically, they would be easy to find and would only need to change once as the business logic changes.

This approach seems relatively simple and straight forward. Why then, has it been generally rejected in favor of the typical object oriented coupling of data with methods?

答:
my perspective is that the purpose of an object should be to contain data.

Yes, but that's not all.

Standard protocol in object oriented design seems to be to include business logic in class definitions.

Not protocol. It's central to Object Orientation. Data + Operations.

The problems, as I see them, start when processes are bound to an object.

You are touching on a central issue - what Data and what operations belong in a given class? As a general guideline I want operations that are "atomic" - I can't think of a better word - to that class.

Consider a simple String.Equals()

You are not thinking object oriented!

```<code>// this is C#
public class Location {
    public string Country { get; set; }

    public override bool Equals(object other) {
        if(other == null)
            return false;
        if(! other is Location)
            return false;

        return this.Country == other.Country;  // we're taking advantage of String.Equals(). cool.
    }
}

// sample use
// Given: Odessa, OdessaUSA, OdessaRussia are Location objects.

if(Odessa.Equals(OdessaUSA))
    Console.WriteLine ("Hot damn! I'm in Texas");

if(Odessa.Equals(OdessaRussia))
    Console.WriteLine ("Hot damn! Cheap Vodka");
</code>```

... And eventually as the system expands, more hours are wasted searching through the code than analyzing it.

The way you're presenting it, I agree. This is a good example of why you'd want to write Object Oriented.

it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives.

No, this is anathema to Object Orientation. Each class has it's own "equals" definition. Any changes affect objects of that class only. It does not affect every string property, or equals method, of every class. An essential characteristic of a Class is that it encapsulates it's own data and operations. Changes to one class do not affect another.

Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different.

All objects of the same class have the same equals() definition. In OO you cannot compare objects of different classes - i.e. types. It makes no sense any more than trying to perform equals on a string to a numeric.

Body:
my perspective is that the purpose of an object should be to contain data.

Yes, but that's not all.

Standard protocol in object oriented design seems to be to include business logic in class definitions.

Not protocol. It's central to Object Orientation. Data + Operations.

The problems, as I see them, start when processes are bound to an object.

You are touching on a central issue - what Data and what operations belong in a given class? As a general guideline I want operations that are "atomic" - I can't think of a better word - to that class.

Consider a simple String.Equals()

You are not thinking object oriented!

// this is C#
public class Location {
    public string Country { get; set; }

    public override bool Equals(object other) {
        if(other == null)
            return false;
        if(! other is Location)
            return false;

        return this.Country == other.Country;  // we're taking advantage of String.Equals(). cool.
    }
}

// sample use
// Given: Odessa, OdessaUSA, OdessaRussia are Location objects.

if(Odessa.Equals(OdessaUSA))
    Console.WriteLine ("Hot damn! I'm in Texas");

if(Odessa.Equals(OdessaRussia))
    Console.WriteLine ("Hot damn! Cheap Vodka");

... And eventually as the system expands, more hours are wasted searching through the code than analyzing it.

The way you're presenting it, I agree. This is a good example of why you'd want to write Object Oriented.

it makes far more sense that a generic equals rule is defined that modifies its behavior polymorphically depending on the inputs it receives.

No, this is anathema to Object Orientation. Each class has it's own "equals" definition. Any changes affect objects of that class only. It does not affect every string property, or equals method, of every class. An essential characteristic of a Class is that it encapsulates it's own data and operations. Changes to one class do not affect another.

Now, assume I have a thousand such different objects with different equals() definitions, some of which are the same, and some of which are vastly different.

All objects of the same class have the same equals() definition. In OO you cannot compare objects of different classes - i.e. types. It makes no sense any more than trying to perform equals on a string to a numeric.


问:
Where to put format validation in a CQRS “stylish” domain model?
It feels right to put format validation inside the domain objects (VOs or entities) because it is the natural place for high cohesion and the domain knows best what every domain description/attribute/property means. Many DDD practitioners and books authors (Vaugh Vernon, Dan Bergh - and even Eric Evans suggest , but on a different aspect: authorization, to model the domain to reflect these matters) suggest to design the domain model in a way to reflect and enforce a proper state of the business.

I agree that format validation (ie.: address property in EmailAddress VO should be max ~250 chars and should match a regex) should be implemented inside the domain objects. But these validation checks work best with a domain model that will be used for both state changes and state queries.

What about CQRS where the command side (where the domain model is) has little or no knowledge about the read side. Should one reimplement the same input format checks in the query side of the application? In CQRS there are some common responsibilities for both command and query side (like input format validation), so the usual format validation implementations that most of DDD practitioners suggest will be duplicated.

How should one deal with this, w/o making the domain model (from the command side) to be anemic and w/o making unaware of the state of the attributes it will hold .

An example : there might be a feature that would let a conference owner to schedule a conference and change the number of available seats. But because the conference room is not big enough, the maximum allowed number of seats would be 100. So a business rule would be that : a conference owner cannot add more than 100 seats for a scheduled conference (also minimum 1 seat needed for the conference to be in a valid state). So a method would be on a ConferenceAR :

```<code>changeNumberOfAvailableSeats(numberOfAvailableSeats) {
    if(!isNumber(numberOfAvailableSeats) || numberOfAvailableSeats > 100 ||
            numberOfAvailableSeats < 1) {
        throw new DomainException ...
    }

    // Change the number of available seats ...
}
</code>```

On the query side there might be an UI page where you can find all the scheduled conferences that have a certain number of available seats. So again , on the server's query side of the application, there must be a format validation that will check if the query for scheduled conferences with a number of seats available is a number and is in the range 1-100. This query might be needed by someone who wants to reserve a certain number of seats for a conference . Also conferences might be on the same topic so one could see a conference with the same topic many times and choose the one cheaper or with more seats available.

So again, should one reimplement the format validation on both query and command sides or there is another solution?

P.S. : there are many format validation duplicates (on both command and query side) like the email format validation , or a currency format validation (if the currency is : USD || CAD || AUD etc ...)

P.P.S. : Another question that popped up : Does the query side of the application require any input format validation ? If the input is not a valid format it will return nothing , query found no data related to the request. I see that format validation on the query side is purely a security measure (ie. for buffer overflows). So is the input format validation really required on the query side ?

答:
I would think if your domain objects on the command side are always in a valid state, you shouldn't need to worry that the queries return invalid results.

What would you do, anyway, if you discovered an invalidity on the read-side, anyway? Tell the read repository to re-enter the values? ;-)

If the read side were to have checking, it would think it would be in the area of some kind of unit or integration testing, because instead of a data entry error message, it's a bug.

One of the things about CQRS is prying apart those concerns, plus just having stuff in one place. Otherwise it makes it harder, not easier (really, it can be as easy or easier, otherwise, look for a better way to implement it or keep studying it).

OwnerDisplayName: Tudor


问:
how to approach pharmacy software project
I would like to complete a pharmacy software proof concept. But I have a few questions I do not know.

Physician information

In order to refill or dispense a new RX the software needs to have access to a database of current doctors, is there a downloadable database or a service I can interact with to get a list of current practicing doctors ?

Medication information

needs to access a database of medications, which I believe companies like Medispan offer for a price. How much does interacting with these kinds of companies cost.

Billing

How can I interface be it with an insurance company, medicare, medicaid, etc for billing ? I have seen these programs are able to submit orders and get a response automatically for how much was billed and how much was paid etc.

What I have done

I started to just work on  basic windows form application which would be the client and then I imagine I would have to connect it to my server in order to perform authentication etc before I billed for them from the server.

Are the client applications connecting with the APIs directly or just an intermediary web service which in turn does all the work ?

I also found one open source project http://www.anshealth.com/ but it seems like its pretty complicated to setup and there isn't much documentation. There hasn't been a post in their forums since last year.

Edit

I edited my question in order to make it more specific, I have asked specifically three questions.

答:
Large software products start out as small software products and feature creep from there until it does everything the customer wants it to.  Rarely are large products made ex nihilo.

Start small - very small - and increment.

You write the smallest simplest thing you can that works in the realm.  Inventory tracking for example.  Just write some code that handles inventory and have it grow from there.  Once that piece works and could potentially be used, you find potential customers about what it lacks... then you write that piece.  And keep going.

Learn from the big

The other option is to get a job in a company that actually has that in its realm of core competencies and has a product that you can sit down with and work to understand.  This will let you get a better understanding of the entire architecture of the product.

Study the regulations

If you are trying to write a point of sales register, make sure you understand the PCI security standards so that your software doesn't run afoul of it.  If you are working on trying to write something that fits into the healthcare industry, you will want to know and understand HIPAA.  Neither of these are small things.

These regulations are part of the reason that the bar is so high - you will probably need a lawyer or an auditor familiar with the regulations (or both) to help you through the process.

In healthcare, there's also a fair amount of liability issues that you will want to work through with the lawyer.

You'll need to pay for the access

The companies that hold those huge amounts of data that they've built and collected over the years - the prescription drug databases with interactions and such... the way they make money is they sell access to that data.  They don't just give it away for free.

You will need to come to licensing terms with them.

And each company that you need to work with, you will need to work with.  Thats rather obvious, but well, you need to do the research for how to work with insurance providers (it may be you have a printer and a form next to it that runs a report each week and gets sent out or something... I don't know, I haven't researched it).

This is a very large product for one person (or even a small team)

This isn't something that you'll easily be able to dive into.  It just isn't - the regulations, the companies that want printed reports with carbon paper because they haven't modernized yet. That system that only speaks EDI.

When you put all these parts together, it isn't a simple windows form that the pharmacist sees.  Its a huge system of multiple parts that don't always fit together well and have grown organically over the past few decades.

The companies in this realm often have decades of entrenchment.  If you want to learn about all the parts that are there - get a job with one of them to get a better idea of the scope of the software.  I may be wrong about all I said (it may be easier, it may be much worse)... but I do know that this is a huge undertaking.

(I'm basing this off of I know how to write a point of sales system... and its a lot bigger than I thought it would be a decade ago... and thats 'easy' with the biggest liabilities being the mismatch of price and posted price in Michigan.  Going to healthcare I can only imagine its much more complex... a register doesn't need to post an alert if someone buys regular nails and treated lumber at the same time)


问:
Do you have any techniques to help you get started in the morning?
I'm not a morning person.  I got into the habit of working from 10 to 7/8, sometimes 9.

Nevertheless, many of the places I've worked for have asked for something more like 8 to 6 or 9 to 6.

Honestly, I have a real tough time getting my brain going in the morning and getting into the code.  Once I do, I can concentrate for a long time and be quite productive.

It's getting into the code and starting to get going with it that I have trouble with.  Sometimes I will waste time in the morning just because I can't focus on the problem (yes, I am writing this in the morning).

I've put all my busy work in the morning, but as a developer, I don't have a lot of busy work.

It kind of becomes a self reinforcing thing; because you don't get things done in the morning, you have to stay later.  Because you have to stay later, then its harder to get started the next morning, etc.

Do other people have trouble with this?  If so, any techniques you've learned?

Thanks!

答:
I'd be tempted to suggest seeing if you have any sleep problems as if does take you a while to get going in the morning this may be a symptom of sleep apnea which can be treated.  This is just a suggestion as I do have it and what I do to treat it has worked well for me.

The other suggestion I'd make is to consider getting up earlier and trying to exercise to see if that helps get you going or not.  Usually I exercise around lunch time for a half hour as that is where I can use a reset that happens when I take that walk and reflect on nearly anything and everything that comes to me.


答:
Interviews!

Reversing a string (in place or not) is a very common interview question for basic programming knowledge. A language lacking these built in functions would be difficult to interview for. The candidate would actually have to know something.1

1: This is a tongue-in-cheek answer.

Title: What do you use string reversal for?

Body:
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.


答:
GYM

Although not the first choice for a stereotypical programmer, I find going to the gym before work very good for waking you up in the mornings. Not only is it good for you, but the exercise actually increases your energy levels, making you feel more awake and alert early in the morning plus with the added endorphins in your body, you'll feel better about going to work. It doesn't have to be a body-pounding routine to make Arnie look like a whimp, just 20 mins on a treadmill and maybe a rowing machine is enough give me a kick in the mornings.

If you suppliment this with a breakfast high in complex carbs (porridge or alpen for the Brits among us) then this will set you up for a good morning.

It doesn't even have to be the gym, just walking a little faster in the mornings or maybe cycling to work (I haven't tried this one, just a suggestion) would have the same effect.

Title: Do you have any techniques to help you get started in the morning?

Body:
I'm not a morning person.  I got into the habit of working from 10 to 7/8, sometimes 9.

Nevertheless, many of the places I've worked for have asked for something more like 8 to 6 or 9 to 6.

Honestly, I have a real tough time getting my brain going in the morning and getting into the code.  Once I do, I can concentrate for a long time and be quite productive.

It's getting into the code and starting to get going with it that I have trouble with.  Sometimes I will waste time in the morning just because I can't focus on the problem (yes, I am writing this in the morning).

I've put all my busy work in the morning, but as a developer, I don't have a lot of busy work.

It kind of becomes a self reinforcing thing; because you don't get things done in the morning, you have to stay later.  Because you have to stay later, then its harder to get started the next morning, etc.

Do other people have trouble with this?  If so, any techniques you've learned?

Thanks!


问:
Coding style - define fields separate or not
Some use this convention:

```<code>private String event;
public getEvent() { return this.event; }
public setEvent(String value) { this.event = value; }

private int id;
... same as above ...
</code>```

In some projects they define all the fields first, all static fields after (or before), all public/private variables, then the setters, getters, other methods.

Which do you use and why?

答: I follow the coding standard proposed by FxCop and checked by ReSharper (C#). Nothing like having automated tools to make sure you follow the rules :)</p>


答:
Sexegers

Sometimes, problems that involve regular expressions can more easily be written by having the input string reversed and tackling the problem in a different way.

Technique courtesy of the man who taught me Perl.

Sexeger on PerlMonks

Title: What do you use string reversal for?


答:
I tend to divide my fields into two categories:  fields that get initialized right away (i.e. through a constructor, or some initialization method that is expected to be called before other operations) and fields that can be set at any time.

I don't follow any concrete rule, but I think I tend to follow this ordering:

1:  Fields that get initialized right away

2:  Constructors, particularly ones that initialize the fields from #1

3:  Initialization methods that will initialize the fields from #1

4:  get/set methods for fields from #1, if applicable.

5:  Other fields that can be set at any time, along with associated get/set methods.

6:  Methods that utilize fields.

Below is some example code that demonstrates this:

```<code>class Example1
{
    // First: Fields with no associated properties,
    // fields with read-only properties,
    // or fields that will be initialized up front (i.e. in a constructor or an initialization method)
    private int _Field1;
    private string _Field2;

    // Second: Constructors
    public Example1(int field1, string field2)
    {
        _Field1 = field1;
        _Field2 = field2;
    }

    public Example1() : this(0, null) { }

    // Third: Methods that initialize fields
    public void InitializeWithExampleData(ExampleDataObject data)
    {
        _Field1 = data.Value1;
        _Field2 = data.Value2;
    }

    // Fourth: Properties for all fields that were previously declared
    public int Field1
    {
        get { return _Field1; }
    }

    public string Field2
    {
        get { return _Field2; }
    }

    // Fifth: Other Fields along with read/write properties
    // i.e. fields that are not initialized by any constructors or methods declared above
    private int _Field3;

    public int Field3
    {
        get { return _Field3; }
        set { _Field3 = value; }
    }

    private string _Field4;

    public string Field4
    {
        get { return _Field4; }
        set { _Field4 = value; }
    }

    // Sixth: Methods that utilize fields
    public int CalculateSomethingBasedOnFieldValues()
    {
        return this.Field1 + this.Field2.Length + this.Field3;
    }
}

struct Example2 // Immutable type example
{
    // First: Fields
    private int _Field1;
    private string _Field2;

    // Second: Constructors (i.e. things that can write to the fields)
    public Example2(int field1, string field2)
    {
        _Field1 = field1;
        _Field2 = field2;
    }

    public Example2(int field1)
    {
        _Field1 = field1;
        _Field2 = null;
    }

    // Third: Properties (i.e. things that can read from the fields)
    public int Field1
    {
        get { return _Field1; }
    }

    public string Field2
    {
        get { return _Field2; }
    }
}
</code>```

As I mentioned, I'm flexible, but I tend to do this because I think the order of the declarations tends to follow the order of operations that involve the fields, and that makes me happy inside.

First, the fields are declared (i.e. memory is allocated to them).  Second, they are set, either through a constructor or an initialization method.  Third, they are read, or they are utilized by some other method to perform an operation.

Fields that have both a get and a set method do not clearly follow this flow, since they could be set at any time by a consumer calling the set method, which is why I tend to separate them into a different area.

Title: Coding style - define fields separate or not

Body:
Some use this convention:

```<code>private String event;
public getEvent() { return this.event; }
public setEvent(String value) { this.event = value; }

private int id;
... same as above ...
</code>```

In some projects they define all the fields first, all static fields after (or before), all public/private variables, then the setters, getters, other methods.

Which do you use and why?

Body:
I tend to divide my fields into two categories:  fields that get initialized right away (i.e. through a constructor, or some initialization method that is expected to be called before other operations) and fields that can be set at any time.

I don't follow any concrete rule, but I think I tend to follow this ordering:

1:  Fields that get initialized right away

2:  Constructors, particularly ones that initialize the fields from #1

3:  Initialization methods that will initialize the fields from #1

4:  get/set methods for fields from #1, if applicable.

5:  Other fields that can be set at any time, along with associated get/set methods.

6:  Methods that utilize fields.

Below is some example code that demonstrates this:

class Example1
{
    // First: Fields with no associated properties,
    // fields with read-only properties,
    // or fields that will be initialized up front (i.e. in a constructor or an initialization method)
    private int _Field1;
    private string _Field2;

    // Second: Constructors
    public Example1(int field1, string field2)
    {
        _Field1 = field1;
        _Field2 = field2;
    }

    public Example1() : this(0, null) { }

    // Third: Methods that initialize fields
    public void InitializeWithExampleData(ExampleDataObject data)
    {
        _Field1 = data.Value1;
        _Field2 = data.Value2;
    }

    // Fourth: Properties for all fields that were previously declared
    public int Field1
    {
        get { return _Field1; }
    }

    public string Field2
    {
        get { return _Field2; }
    }

    // Fifth: Other Fields along with read/write properties
    // i.e. fields that are not initialized by any constructors or methods declared above
    private int _Field3;

    public int Field3
    {
        get { return _Field3; }
        set { _Field3 = value; }
    }

    private string _Field4;

    public string Field4
    {
        get { return _Field4; }
        set { _Field4 = value; }
    }

    // Sixth: Methods that utilize fields
    public int CalculateSomethingBasedOnFieldValues()
    {
        return this.Field1 + this.Field2.Length + this.Field3;
    }
}

struct Example2 // Immutable type example
{
    // First: Fields
    private int _Field1;
    private string _Field2;

    // Second: Constructors (i.e. things that can write to the fields)
    public Example2(int field1, string field2)
    {
        _Field1 = field1;
        _Field2 = field2;
    }

    public Example2(int field1)
    {
        _Field1 = field1;
        _Field2 = null;
    }

    // Third: Properties (i.e. things that can read from the fields)
    public int Field1
    {
        get { return _Field1; }
    }

    public string Field2
    {
        get { return _Field2; }
    }
}

As I mentioned, I'm flexible, but I tend to do this because I think the order of the declarations tends to follow the order of operations that involve the fields, and that makes me happy inside.

First, the fields are declared (i.e. memory is allocated to them).  Second, they are set, either through a constructor or an initialization method.  Third, they are read, or they are utilized by some other method to perform an operation.

Fields that have both a get and a set method do not clearly follow this flow, since they could be set at any time by a consumer calling the set method, which is why I tend to separate them into a different area.


答:
ASCII isn't the best encoding for genetic information (you can pack the base types ACGT as
2bits). Pack them into an array of longlongs and you get 32 genetic "letter" per word. DNA
can get turned around, so you got to check a chunk of DNA against both forward are reverse copies of a test sequence. So being able to reverse a packed string of 2bit quantities can
be very useful for various sorts of genetic analysis.

I had as an item on a benchmark for spy agencies, how fast can you reverse the bits it a long-long (actually a very long array of long-longs). The obvious method of exchanging 2bits at a time is much slower than the less obvious methods. These are related to some of the neat
algorithms for in place array transposition.

Tangurena:
  The operation you refer to is called a population count. Similar desirables for bit packed data are leading and trailing zero count. There are a lot of really neat things
that one can do with bit packed data. A single operation on a longlong is 64way data parallel, so if you know what you are doing you can get incredible performance for certain types of computataions.

Title: What do you use string reversal for?


答:
Well, this is a tongue-in-cheek answer.

"Back in the day" I owned a Unix box, and it had an ordered dictionary file of English words, used for spell-checking.

I made a new file by reversing all the words in the dictionary, sorting it, and then reversing them again. The result was a list of words sorted from right-to-left.

So if you searched it for a word, next to that word would be words with similar endings. So it was easy to make little poems!

You can really amuse yourself when you see what rhymes with what.

Title: What do you use string reversal for?


答: I'll usually define the fields that a property works with and the specific property, then the constructors, then methods. Generally speaking private methods that are related to specific public methods will be grouped together.</p>


答:
Anything where working with the reversed string is easier.

Working with integers as strings is a lot easier if the strings are reversed.
I built some library functions for doing math with large integers and used string reversal to make the arithmetic functions simpler.

Granted, I've only used it for cranking out answers on Project Euler, but still, the original premise holds.

Title: What do you use string reversal for?


答:
In natural language processing & parsing, sometimes it is easier to search a string from the end to the beginning.  A string reverse would be useful for debugging, or as an alternate way to write the loop (reverse the string and then loop from index 0 to n-1).

Also some languages are written right to left, so a string reverser could be used for that if you were in an environment that didn't natively recognize LTR/RTL languages.

A string (in some languages) is an array of chars, but it could just as well be paychecks or inventory modifications. In a loop moving across these, you might be do some calculations that should be the same regardless to what order you process them.  A perfectly cromulent unit test would be to check to see if they the calculations apply the same going forward or going backward.  This might be trivially obvious for addition, maybe not for other more opaque operations.

Title: What do you use string reversal for?


答: Maybe low-cost multi-lingual support, for languages that use letters right-to-left (such as Arabic), instead of left-to-right. Of course you have to watch out for accent characters modifying the right character...</p>

Title: What do you use string reversal for?


问:
How can you learn to design nice looking websites?
I am a moderately capable web developer. I can put stuff where I want it to go and put some JQuery stuff in there if I need to. However, if I am making my own website (which I am starting to do) I have no idea how to design it. If someone was to sit next to me a point to the screen and say "put this picture there, text there" I can do that quite easily. But designing my own site with my choice of colours and text will look like a toddler has invented it.

Does anyone know any websites/books I can look at or has anyone got any tips on the basics of non-toddler web design?

答:
Ogilvy on Advertising: this book covers some basics of graphic design as well as a lot of common sense in making any kind of flyer, ad, etc. even if it was written way before the www era.    </p>

<p>More generally, browse books and magazines on graphic design, fine art, interior decoration, filmmaking - there are a lot of common design principles for making something visually attractive and making information or other content appealing.    Kind of like how electromagnetism is common to electronics, planetary science, chemistry, nuclear and other fields of physics and engineering.  </p>

Body:
Ogilvy on Advertising: this book covers some basics of graphic design as well as a lot of common sense in making any kind of flyer, ad, etc. even if it was written way before the www era.

More generally, browse books and magazines on graphic design, fine art, interior decoration, filmmaking - there are a lot of common design principles for making something visually attractive and making information or other content appealing.    Kind of like how electromagnetism is common to electronics, planetary science, chemistry, nuclear and other fields of physics and engineering.


答:
Another good book in this space would be The Design of Everday Things.  It covers a lot of the practical ideas like favoring designs that lend themselves to easy usage by taking advantage of how people naturally approach a new thing.  The book isn't specifically about UI or web design, but does cover that a bit, I believe.

An early example in the book is doors.  He talks about how doors with a knob or handle on one side and visible hinges are intuitive, because you know the door the will open by pushing or pulling on that side. Fancy doors with hidden hinges, push bars across the whole door, or centered knobs are tricky and require a moment of experimentation because they're operation isn't intuitive.

Title: How can you learn to design nice looking websites?

Body:
I am a moderately capable web developer. I can put stuff where I want it to go and put some JQuery stuff in there if I need to. However, if I am making my own website (which I am starting to do) I have no idea how to design it. If someone was to sit next to me a point to the screen and say "put this picture there, text there" I can do that quite easily. But designing my own site with my choice of colours and text will look like a toddler has invented it.

Does anyone know any websites/books I can look at or has anyone got any tips on the basics of non-toddler web design?


问:
How does the contribution part of "contributing to an open source project" take place?
Note: this question is about the general case... How things usually are.

OK so I can download the code and mess around with it, but how do my changes make it into the project officially? Who decides what changes make it into the project, and how? Is there often a list of required changes/additions? What if I have a cool idea that is not mentioned there? How do I get it approved? And what if two people implement the same feature. Who chooses which implementation makes it into the project?

Basically, how is the whole thing managed (in the general case)?

答:
It really depends on the project. Generally speaking, the larger the project, the more formal the process for new contributors is. If you improve the source of a small project, a simple mail to one of the developers might be enough.

Before you implement a new feature, you should ask them if someone is already working on that. And you should work on the very latest version available, not the latest major/stable build. Otherwise, your changes might be harder to incorporate with the current version.
I can only guess what happens when two people independently implement the same feature, either the first one wins (because nobody knows of the other version) or the decision is based on the quality of the contributions.

Sometimes there is a list of todo-features, but more often, you just implement what you need for your own needs. You fix the bugs that bugger you.


答: One tool I find invaluable in design is Color Scheme Designer.  I typically pick a color I'd like to base the design around and then use the "Analogic" scheme to get a nice set of matching colors.  To me, getting the colors right is the worst part, so after that the rest is just getting a nice layout and applying the limited palette of colors.</p>


答: Look at the files that come with the software, and anything else available like a project website.  Except for really small projects, there should be some guidelines or even hard rules.  If not, you should at least have the email address of the project owner.  As ammoQ points out, getting in touch with the owner is a good idea in any case, but you're more likely to be taken seriously if you've read the rules or guidelines.</p>

Title: How does the contribution part of "contributing to an open source project" take place?

Body:
Note: this question is about the general case... How things usually are.

OK so I can download the code and mess around with it, but how do my changes make it into the project officially? Who decides what changes make it into the project, and how? Is there often a list of required changes/additions? What if I have a cool idea that is not mentioned there? How do I get it approved? And what if two people implement the same feature. Who chooses which implementation makes it into the project?

Basically, how is the whole thing managed (in the general case)?


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答:
Functional languages!

Learning functional languages makes you think in terms of expressions, rather than steps and named mutable states (variables). This has a significant impact on your ability to effectively deal with every-day programming problems - especially now that almost every popular language has functional features.

Algorithms and complexity theory is also important, but it is somewhat less interesting in that it mostly lets you put names on stuff that you usually already knew and could deduce.


答:
You can't go far wrong with mailing a patch for a bug fix or feature you like.

If there's any documentation on how/what/where to submit be sure to follow that.
Otherwise send a patch with some description of what it does (and why that's a good thing) to the project mailing list. If there's no mailing list send it to the e-mail address listed on the website.


答:
Wake Up

Smoke

Have shower with hot & cold water every morning

Some coffee or tea

Start coding yesterday evening list


问:
REPL - Do You Find It Useful?
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?

答:
I often do exploratory programming (for example to find out how to design an API). This often goes in one of two ways: either I actually use only REPL, or I use REPL to actually test manually whatever I wrote in an editor. In both cases REPL saves me huge amounts of time.

Also, REPL is the best for throw-away programming: when you have a task that you know you probably wont perform it again: f.e. for data mining (Sage+R and Python are brilliant for that) there are cases you might never have data in the same exact format, so you'd need to write routines to import specific files.

Title: REPL - Do You Find It Useful?


问:
Is it acceptable to work around Apache's .htaccess nonsense in another language?
I'm getting sick of all of Apache's quirks, and I'm considering starting to avoid .htaccess as much as I can in favor of writing actual, predictable code. It would be easy and straightforward to emulate things like file security and rewrites, and control precisely what is and isn't inherited between directories without having to use strange, obtuse directives. Would there be any downsides to this?

I'm talking about replacing, for example, this:

```<code># .htaccess
RewriteCond %{HTTP_USER_AGENT} blah
RewriteRule ^(.*)$        /test$1 [R=301,L]
</code>```

with something like this:

```<code># PHP, in a header file
if(strpos($_SERVER['HTTP_USER_AGENT'], 'blah') !== false)
    redirect(301, '/test' . $_SERVER['REQUEST_URI']);
</code>```

To repeat the question, what would be the downsides of implementing functionality in PHP which is traditionally handled by .htaccess?

答:
Performance, probably...

Also, the two behaviors you describe are not the same - a rewrite is not the same as a 301 redirect.


答:
I have written a framework for my own use that gets rid of all rewrites but one - rewrite (not redirect) everything to a single index.php.  That index.php creates an instance of the framework controller and then tells it what paths exist in the site:

```<code>// Create paths for this site
$controller->addPath('/path', 'templatename, 'MyClass::someCodeToRun');
</code>```

Of course there is more to it than that (mainly dynamic paths, nested templates, and security), but that's the basic idea.

This is what many frameworks do, and I really recommend it - it doesn't need to come at (much) of a performance price if your framework is lightweight and you only include what you need for each path.  The only performance price is essentially the lookup table (which is just an associative array) for which path does what.

I think the better code organization can often end up being a performance win.

Title: Is it acceptable to work around Apache's .htaccess nonsense in another language?

Body:
I'm getting sick of all of Apache's quirks, and I'm considering starting to avoid .htaccess as much as I can in favor of writing actual, predictable code. It would be easy and straightforward to emulate things like file security and rewrites, and control precisely what is and isn't inherited between directories without having to use strange, obtuse directives. Would there be any downsides to this?

I'm talking about replacing, for example, this:

```<code># .htaccess
RewriteCond %{HTTP_USER_AGENT} blah
RewriteRule ^(.*)$        /test$1 [R=301,L]
</code>```

with something like this:

```<code># PHP, in a header file
if(strpos($_SERVER['HTTP_USER_AGENT'], 'blah') !== false)
    redirect(301, '/test' . $_SERVER['REQUEST_URI']);
</code>```

To repeat the question, what would be the downsides of implementing functionality in PHP which is traditionally handled by .htaccess?

Body:
I have written a framework for my own use that gets rid of all rewrites but one - rewrite (not redirect) everything to a single index.php.  That index.php creates an instance of the framework controller and then tells it what paths exist in the site:

// Create paths for this site
$controller->addPath('/path', 'templatename, 'MyClass::someCodeToRun');

Of course there is more to it than that (mainly dynamic paths, nested templates, and security), but that's the basic idea.

This is what many frameworks do, and I really recommend it - it doesn't need to come at (much) of a performance price if your framework is lightweight and you only include what you need for each path.  The only performance price is essentially the lookup table (which is just an associative array) for which path does what.

I think the better code organization can often end up being a performance win.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答: I don't think so, unless you are already in the niche market where COBOL is still maintained.</p>

Title: Is COBOL still worth learning?


问:
As a programmer, what paths should I take concerning education?
After a burst of ranting about homework, the applicability of the classes I'm taking, and my computer science teacher, I have some questions concerning education for my career path as a developer.

I taught myself everything I know about programming. I've been thinking lately about the advantages of teaching myself vs. learning from a teacher. I feel I might miss some things I would normally learn. I might learn some concepts wrong, or something. After all, computer science eduction has been around longer than I have.

The problem is, I'm not learning anything new about computer science in my programming class. I put the computer programming 2 course on my schedule (it was labeled as Computer Science when I signed up for it). It turns out that it's just learning C++ and of course OOP. In fact, the CP2 students are in the same classroom at the same time as the CP2 students, except the CP1 course is a half-year class instead of full year. I thought we'd do something like data structures (other than arrays), or something I'm less experienced in. The teacher had me change my schedule to CP1, but he "lets me loose" to work on projects with the CP2 students while he teaches the CP1 students.

I usually end up helping the CP2 students with build errors and things like that after I'm done. I certainly don't mind helping them, but I'm not learning anything new, and I likely won't, seeing that AFAIK linked lists will be the most advanced concept taught (for the CP2 students; The class ends this semester for CP1, including me). Frankly, I'm not interested in copying source code from paper to screen, which is 90% of what the CP2 students do.

I want to be learning something computer science related. I'd hate to sit around waiting for my options to catch up. I want to take classes not offered by my high school, like discrete mathematics, algorithms and data structures, or something like that.

So my question is, where can I take classes which aren't offered by my high school? Can I take college classes? (keep in mind there isn't any concurrent, AP, or distance-ed classes concerning computer science offered by my high school besides the CP1/CP2 class I'm in). Do you know any online classes I could take?

Thanks,
Danny Shields

P.S: I talk about my programming experience on my StackExchange profile if it helps.

答:
I know exactly how you feel.

I want to be learning something computer science related. I'd hate to sit around waiting for my options to catch up. I want to take classes not offered by my high school, like discrete mathematics, algorithms and data structures, or something like that.

Sure! Lots of high schools have programs to pay for college or correspondence courses that the school doesn't offer. Even if they don't that's no reason you can't use some of the many available online tutorials, white papers, specification guides, and code to increase your knowledge outside of a classroom. Now you have practical applicable experience for when you do end up taking courses.

So my question is, where can I take classes which aren't offered by my high school? Can I take college classes? (keep in mind there isn't any concurrent, AP, or distance-ed classes concerning computer science offered by my high school besides the CP1/CP2 class I'm in). Do you know any online classes I could take?

My high school had Intro to Computer Science (Visual Basic) and AP Computer Science (Java). Considering I took AP Comp. Sci in 8th grade it wasn't much help to take either. This doesn't restrict you. What stops you from learning outside the classroom? I was brutally efficient in completing coursework to increase the amount of time I could spend learning on my own. When you get stuck you have an instructor that's probably as bored as you are teaching about Arrays vs. Linked Lists. They (normally) love to see students excel outside the course parameters.


问:
How can I judge whether a project is particularly complex or if I'm just slow in picking it up?
I'm making little progress on a major project.  The source is massive, many layers of objects, macaroni code, double-diamond graphs of multiple inheritance, half-baked features frozen when the original writer left, and no one knows why many pieces of it were designed the way they were.

I suppose any competent programmer would have some trouble figuring it all out well enough to fix bugs, finish the half-baked stuff and add new features.  However, I suspect I'm going slower than a typical programmer.

How do I judge whether the source is unusually bad and I'm just doing as well as anyone could, versus the source is typical for a project like this and I'm just slow-witted or underskilled?

答:
First off, I would not spend too much time worrying that you might be "slow-witted or underskilled." Some projects are hard to grasp, and large projects often take a while to get up to speed on. Thinking that you are "stupid" or not up to the task will not help you in any way.

It sounds like you need help with the code, so consider your resources. Do you have access to the original coders? If they are available, they could be good resources for information. What documentation is available? If documentation is scarce, pull out a notebook and start creating your own personal documentation.

The big idea here is that you should expect this process to take time, and the less time you spend mentally beating yourself up, the more energy you'll have to analyze the code and figure it out. Good luck!


答:
The only way to decide that question is to acquire a lot more programmers to tackle the same issue and see if they fare better.

This is of course rarely practical, the task has fallen to your good self and providing you are doing the best you can on it, researching where your knowledge fails you.  Breaking it apart where the complexity foxes you and keeping whoever cares well informed of your progress.  Then I would not worry and keep at it.

Title: How can I judge whether a project is particularly complex or if I'm just slow in picking it up?

Body:
I'm making little progress on a major project.  The source is massive, many layers of objects, macaroni code, double-diamond graphs of multiple inheritance, half-baked features frozen when the original writer left, and no one knows why many pieces of it were designed the way they were.

I suppose any competent programmer would have some trouble figuring it all out well enough to fix bugs, finish the half-baked stuff and add new features.  However, I suspect I'm going slower than a typical programmer.

How do I judge whether the source is unusually bad and I'm just doing as well as anyone could, versus the source is typical for a project like this and I'm just slow-witted or underskilled?