答:
It depends on your design, typically I would not return exceptions to a caller, rather I would throw and catch them and leave it at that.  Typically code is written to fail early and fast.  For example consider the case of opening a file and processing it (This is C# PsuedoCode):

```<code>        private static void ProcessFileFailFast()
        {
            try
            {
                using (var file = new System.IO.StreamReader("c:\\test.txt"))
                {
                    string line;
                    while ((line = file.ReadLine()) != null)
                    {
                        ProcessLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

        private static void ProcessLine(string line)
        {
            //TODO:  Process Line
        }

        private static void LogException(Exception ex)
        {
            //TODO:  Log Exception
        }
</code>```

In this case, we would error out and stop processing the file as soon as it encountered a bad record.

But say the requirement is we want to continue processing the file even if one or more lines has an error.  The code may start to look something like this:

```<code>    private static void ProcessFileFailAndContinue()
    {
        try
        {
            using (var file = new System.IO.StreamReader("c:\\test.txt"))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    Exception ex = ProcessLineReturnException(line);
                    if (ex != null)
                    {
                        _Errors.Add(ex);
                    }
                }
            }

            //Do something with _Errors Here
        }
        //Catch errors specifically around opening the file
        catch (System.IO.FileNotFoundException fnfe)
        {
            LogException(fnfe);
        }
    }

    private static Exception ProcessLineReturnException(string line)
    {
        try
        {
            //TODO:  Process Line
        }
        catch (Exception ex)
        {
            LogException(ex);
            return ex;
        }

        return null;
    }
</code>```

So in this case we return the exception back to the caller, although I would probably not return an exception back but instead some sort of error object since the exception has been caught and already dealt with.  This is no harm with returning an exception back but other callers could re-throw the exception which may not be desireable since exception object have that behavior.  If you wanted callers have the ability to re-throw then return an exception, otherwise, take the information out of the exception object and construct a smaller light weight object and return that instead.  The fail fast is usually cleaner code.

For your validation example, I probably wouldn't inherit from an exception class or throw exceptions because validation errors could be quite common.  It would be less overhead to return an object rather than to throw an exception if 50% of my users fail to fill out a form correctly on the first attempt.

Body:
It depends on your design, typically I would not return exceptions to a caller, rather I would throw and catch them and leave it at that.  Typically code is written to fail early and fast.  For example consider the case of opening a file and processing it (This is C# PsuedoCode):

        private static void ProcessFileFailFast()
        {
            try
            {
                using (var file = new System.IO.StreamReader("c:\\test.txt"))
                {
                    string line;
                    while ((line = file.ReadLine()) != null)
                    {
                        ProcessLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

        private static void ProcessLine(string line)
        {
            //TODO:  Process Line
        }

        private static void LogException(Exception ex)
        {
            //TODO:  Log Exception
        }

In this case, we would error out and stop processing the file as soon as it encountered a bad record.

But say the requirement is we want to continue processing the file even if one or more lines has an error.  The code may start to look something like this:

    private static void ProcessFileFailAndContinue()
    {
        try
        {
            using (var file = new System.IO.StreamReader("c:\\test.txt"))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    Exception ex = ProcessLineReturnException(line);
                    if (ex != null)
                    {
                        _Errors.Add(ex);
                    }
                }
            }

            //Do something with _Errors Here
        }
        //Catch errors specifically around opening the file
        catch (System.IO.FileNotFoundException fnfe)
        {
            LogException(fnfe);
        }
    }

    private static Exception ProcessLineReturnException(string line)
    {
        try
        {
            //TODO:  Process Line
        }
        catch (Exception ex)
        {
            LogException(ex);
            return ex;
        }

        return null;
    }

So in this case we return the exception back to the caller, although I would probably not return an exception back but instead some sort of error object since the exception has been caught and already dealt with.  This is no harm with returning an exception back but other callers could re-throw the exception which may not be desireable since exception object have that behavior.  If you wanted callers have the ability to re-throw then return an exception, otherwise, take the information out of the exception object and construct a smaller light weight object and return that instead.  The fail fast is usually cleaner code.

For your validation example, I probably wouldn't inherit from an exception class or throw exceptions because validation errors could be quite common.  It would be less overhead to return an object rather than to throw an exception if 50% of my users fail to fill out a form correctly on the first attempt.


问:
First of the The Ten Commandments for C++ Programmers by Steve Oualline correctly transcribed?
I do not have the book “Practical C++ Programming” by Steve Oualline but I was reading his Ten Commandments for C++ programmers at The Ten Commandments for C++ Programmers and I was wondering if the first has been correctly transcribed? For reference the transcription is:

Thou shalt not rely on the compiler default methods for construction, destruction, copy construction, or assignment for any but the simplest of classes. Thou shalt forget these “big four” methods for any nontrivial class.

He seems to be advocating manually defining copy construction and copy assignment. Is that a correct interpretation of his first commandment?

Edit: Although at present I am leaving Adrian's answer as the accepted one I would like anyone who views this question to read Jerry's. I did specifically ask whether the above text is accurately transcribed and not about its merit (which is probably a more interesting discussion). But Jerry does make some good points about its merit (or lack thereof) which are similar to my opinions of it. I just wanted to make sure I had the quote right before I constructed a thorough argument of why I disagree with it.

答: For "any nontrivial" class I am sure that is exactly what he is suggesting - and it would certainly be good practice to write an explicit copy constructor or overloaded assignment for such a non-trivial class.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Are there legitimate reasons for returning exception objects instead of throwing them?
This question is intended to apply to any OO programming language that supports exception handling; I am using C# for illustrative purposes only.

Exceptions are usually intended to be raised when an problem arises that the code cannot immediately handle, and then to be caught in a catch clause in a different location (usually an outer stack frame).

Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

This question came up for me because .NET 4's System.IObserver<T>.OnError method suggests just that: exceptions being passed around as error objects.

Let's look at another scenario, validation. Let's say I am following conventional wisdom, and that I am therefore distinguishing between an error object type IValidationError and a separate exception type ValidationException that is used to report unexpected errors:

partial interface IValidationError { }

abstract partial class ValidationException : System.Exception
{
    public abstract IValidationError[] ValidationErrors { get; }
}
```

<p>(The <code>System.Component.DataAnnotations</code> namespace does something quite similar.)</p>

<p>These types could be employed as follows:</p>

<pre class="lang-csharp prettyprint-override"><code>partial interface IFoo { }  // an immutable type

partial interface IFooBuilder  // mutable counterpart to prepare instances of above type
{
    bool IsValid(out IValidationError[] validationErrors);  // true if no validation error occurs
    IFoo Build();  // throws ValidationException if !IsValid(…)
}
</code>```

Now I am wondering, could I not simplify the above to this:

partial class ValidationError : System.Exception { }  // = IValidationError + ValidationException

partial interface IFoo { }  // (unchanged)

partial interface IFooBuilder
{
    bool IsValid(out ValidationError[] validationErrors);
    IFoo Build();  // may throw ValidationError or sth. like AggregateException<ValidationError>
}
```

Q: What are the advantages and disadvantages of these two differing approaches?

答:
Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

Yes. For example, I recently encountered a situation situation where I found that thrown Exceptions in a ASMX Web Service donot include a  element in the resultant SOAP message, so I had to generate it.

Illustrative code:

```<code>Public Sub SomeWebMethod()
    Try
        ...
    Catch ex As Exception
        Dim soapex As SoapException = Me.GenerateSoapFault(ex)
        Throw soapex
    End Try
End Sub

Private Function GenerateSoapFault(ex As Exception) As SoapException
    Dim document As XmlDocument = New XmlDocument()
    Dim faultDetails As XmlNode = document.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace)
    faultDetails.InnerText = ex.Message
    Dim exceptionType As String = ex.GetType().ToString()
    Dim soapex As SoapException = New SoapException("SoapException", SoapException.ClientFaultCode, Context.Request.Url.ToString, faultDetails)
    Return soapex
End Function
</code>```

Body:
Q: Are there any legitimate situations where exceptions are not thrown and caught, but simply returned from a method and then passed around as error objects?

Yes. For example, I recently encountered a situation situation where I found that thrown Exceptions in a ASMX Web Service donot include a  element in the resultant SOAP message, so I had to generate it.

Illustrative code:

Public Sub SomeWebMethod()
    Try
        ...
    Catch ex As Exception
        Dim soapex As SoapException = Me.GenerateSoapFault(ex)
        Throw soapex
    End Try
End Sub

Private Function GenerateSoapFault(ex As Exception) As SoapException
    Dim document As XmlDocument = New XmlDocument()
    Dim faultDetails As XmlNode = document.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace)
    faultDetails.InnerText = ex.Message
    Dim exceptionType As String = ex.GetType().ToString()
    Dim soapex As SoapException = New SoapException("SoapException", SoapException.ClientFaultCode, Context.Request.Url.ToString, faultDetails)
    Return soapex
End Function


问:
Java - Why do we call an array a "vector"?
I am reading a book on Java Programming, and want to confirm I understand the  definition of the word "vector".  Wikipedia says vector is "A one-dimensional array", source http://en.wikipedia.org/wiki/Vector.

Wouldnt it be simpler to call the array simply an array?  Is there any reason we need to use such fancy language as "vector"?  Is there a difference between an array and a vector?

Source: Cracking the Coding Interview, 4th Edition, by Gayle McDowell, page 47.

FAQ

Q - Why didnt you post this on english.stackexchange.com?

A - Because I think only computer science oriented people will have a good answer.

答: In typical usage, an "array" can mean either a single-dimensional array, or a multidimensional array. Also, in mathematics, a matrix is a 2-dimensional array while a vector is a 1-dimensional array.</p>


问:
What aspects make websites load faster?
I want to know what aspects in VPS hosting packages are related to performance for the website which will make it faster in loading for the end useres. And does RAM really matter?</p>

答:
In my experience RAM makes more difference with databases/datastores than with webservers.

Unless you have a complex web application, go for processing power since that would impact performance more than memory!

Edit> I base my experience working with seperate web- and database servers. The web server hardly used any memory while the database server had to be configured so that the RAM basically was a RAM-disk.

With processing power I mean what CPU you are using; processing speed, number of cores. If you have a database on the same VPS then you can consider to add more RAM since that would impact it's performance.

If you're starting out, it really doesn't matter anyway because you need the traffic first anyway. Only when the site is becoming slow and unresponsive is when you should worry about optimization.

ContentLicense: CC BY-SA 2.5

Title: What aspects make websites load faster?


答:
Vectors aren't exactly arrays. Not classical ones anyway. They are dynamic arrays. They can be resized as needed rather than being of a fixed size. They are thus similar to ArrayLists but not quite the same.

ArrayLists differ from Vectors in that Vectors synchronize individual operations which is something you don't want for concurrency purposes in particular per Jon Skeet. Thus Vector has been deprecated in favor of ArrayList but some still call it a Vector.

The name is originally derived from the mathematical term for a 1 dimensional matrix. This is in spite of the structure actually being an n-tuple.

Title: Java - Why do we call an array a "vector"?

Body:
I am reading a book on Java Programming, and want to confirm I understand the  definition of the word "vector".  Wikipedia says vector is "A one-dimensional array", source http://en.wikipedia.org/wiki/Vector.

Wouldnt it be simpler to call the array simply an array?  Is there any reason we need to use such fancy language as "vector"?  Is there a difference between an array and a vector?

Source: Cracking the Coding Interview, 4th Edition, by Gayle McDowell, page 47.

FAQ

Q - Why didnt you post this on english.stackexchange.com?

A - Because I think only computer science oriented people will have a good answer.


问:
Converting from web to PhoneGap
I was going through the PhonGap Documentation about how to package your HTML/JS/CSS to a platform specific "native app". They have maintained separate documentations for the separate Cordova versions which seems fine.

I essentially understand most of the things there. But the confusion I have is the disparity or the loss of information in the documentation from the older ones to the newer ones. For an instance, if you take a look at this documentation for the version 2.1.0 about setting up the android project and scroll a bit down, they have mentioned such things:

In the root directory of your project, create two new directories:

/libs

assets/www

Copy cordova-2.0.0.js from your Cordova download earlier to
assets/www

Copy cordova-2.0.0.jar from your Cordova download earlier to /libs

Copy xml folder from your Cordova download earlier to /res

....

Change the class's extend from Activity to DroidGap

Replace the setContentView() line with
super.loadUrl("file:///android_asset/www/index.html");

... and so on which clearly mentions the steps to follow while migrating or creating an app for a specific platform. But upwards from the version 2.1.0, these information are missing.

Like in the newer documentations, all they have is just the regular android setup stuffs and android hello world which we can obviously find on the official android documentation. I tried searching the whole documentation for that version and I could not find any information regarding the steps I mentioned above in the older documentation.

Otherwise how are the readers supposed to know those steps? Am I missing something here or have they provided?

答:
PhoneGap is constantly being improved upon, and one aspect of the platform that has continued to see development is initializing a project.  As new versions are released, there have been steps taken to automate and make this process easier.

In PhoneGap 2.1.0, as you've noted, it appears as if none of the initialization process was automated.  The documentation that you linked to describes the steps to set up a native Android project. The developer is then instructed, as you described, to modify this project manually, adding the source files, libraries, and folder structure necessary for PhoneGap to function.

The PhoneGap version that I'm most familiar with is 2.5.0.  The getting started guide for this version can be found here.  In 2.5.0, the developer is directed to navigate to a specific directory in their Cordova distribution and run a script from the command line.  This script takes arguments relating to where your project will live and some other metadata about it, then creates the native project for you and performs the aforementioned steps of creating the PhoneGap specific project structure and adding the source files.  In addition, it starts you off with a test application, which you can examine and run to start you off, basically their version of "Hello World".

I haven't had the opportunity to use PhoneGap 3.0.0 yet, but it appears as though they've made our lives as developers even easier by moving the bootstrap process from a script to a program installed using node.js' npm.  The usage is mostly the same as 2.5.0, where you pass the metadata about the program you're developing to the script, but now you can run it from anywhere, instead of needing to find the script deep in your downloaded cordova files.  I suspect this process will result in something similar to 2.5.0, where the entire project structure is created for you, including relevant PhoneGap source files, with a helpful "Hello World" type program to get you started.

So, in summation, these parts of the documentation that you describe have been removed because PhoneGap has automated their bootstrap process and now does all this work for you!

If you're interested in seeing some of the further differences between versions of PhoneGap, you can view or download their project, including the documentation, on github.  They tag each version increase, so you can revert to one of the tagged commits to go through and see everything that's different in the source code and docs from release to release.

Title: Converting from web to PhoneGap


问:
Is creating database index part of design, implementation or optimisation process?
There are a few questions around this subject:

Is creating all indexes at the start (design) over engineering?

In reality, I've added indexes after performance issues were found and we 'explain plan' and add indexes as needed (i.e. not for all relationships). Should I just skip creating indexes before it's needed because performance issues will show up anyway and probably the indexes that's already been created aren't being used?

Should indexes be treated as part of requirement/specification? Sometimes I see performance requirements, which is usually vague or random. If they're part of specification, then should managing indexes be part of implementation?

I want to make it a bit clearer and more background. In development, usually the different phases involve different kinds of people (e.g. architects, seniors and juniors). It'd be unusual for juniors to be responsible for the design, for example. So, when some tasks overlap, it becomes unclear who's responsible if, for example, a query takes 2 second.

Defining development phases and responsibilities are also important for non-programmers, e.g. project managers or product owners, because they are needed for planning and costing. A project manager might want to higher an architect to do all database related task only at the start and for a short time. If after product launch, it's found that performance is poor, the PM would like to know who's responsible. I hope you get the idea.

答:
Yes, creating database indexes is part of design, implementation, and optimization.

A large set of indexes are part of the design.  Primary key, and foreign key indexes would fall in this category.  Primary and Unique keys are expensive to enforce without an index.  If you understand the design well enough you can omit some foreign key indexes.  You can also substitute indexes with additional columns for the foreign key index.  If access patterns are well understood additional indexes may be specified.  The primary key and foreign key indexes are essential to join performance and query optimization.  Design will specify keys and indexes which are created during the implementation.

During implementation you will create the indexes resulting from the design.  The logical model from the design may be modified.  This may result in new indexes.  Generally, implementation should result in few new indexes.

Performance issues may uncover access paths for which an appropriate index is not available.  A more complete design or implementation may have uncovered some of these cases.  In other cases, actual use or data distribution may differ from what was expected during design and implementation.  Scale and index value distribution can have a significant impact on the value of an index to a query, and the optimized query plan.

Adding all the query indexes which might be, or are expected to be, needed at design or implementation time would be overkill.   Each index carries an overhead, and too many indexes can be costly.

Some reasons an index may not be useful include:

Access path is rarely or never used;

The query optimizer may choose a different access path; or

A partial index provides a sufficiently small set of records.


答:
RAM matters hugely.

The usual suspects apply: how many cores are on the machine, the speed of the cores, the number of VPS sessions, the number of concurrent website users, etc.

I would guess that more RAM is probably the most significant first thing you can do to increase performance.  RAM affects your ability to cache, your ability to serve pages; RAM affects everything.

Title: What aspects make websites load faster?

Body: I want to know what aspects in VPS hosting packages are related to performance for the website which will make it faster in loading for the end useres. And does RAM really matter?</p>


问:
Is SQL important if I know ORM frameworks well?
I don't have any serious experience in SQL and I even hate to write SQL instead of LINQ. I am happy enough with ORMs.

From the employers and sector view point, is it important to know SQL? Do I have to master on it? Are companies that prefer pure SQL over ORM frameworks a "dinosaur" in the programming world?

答:
Yes, you still need SQL.

Do not jump to the assumption that something "old" is somehow unworthy of consideration.  So called "legacy" technologies are those that are still around after having stood the test of time.  We don't call Wang computers "legacy", they failed, and are gone.

If you ask me does it bother me that my bank is probably using COBOL on a mainframe, or IBM i?  Absolutley not.  These are rock solid, tried and true technologies.  Guess what, they are mostly using DB2 SQL.  I'm much happier trusting my money there, than in software developed in a fashionable language of the month.

The dinosaurs lasted on this earth much longer than we humans have been around.  And if you read Jurasic Park (yes, books are better than movies) then I ask you, do you really want to face a pack of hyper-clever velociraptors, or a dogged T-Rex that never gives up?  Don't get bitten by underestimating the "dinosaurs". ;-)


答:
Creating indices is an implementation detail, I wouldn't consider them to be part of a specification. Your database structure design usually only involves the table & column names and data types, not the DDL that will be used to create it - and that is where CREATE INDEX would be included.

For most complicated table relationships, you won't have indices on all possible combinations of keys as that doesn't make sense w.r.t. the business logic. You should create them at start on all the commonly used entity keys & JOINs, and imho just use Explain Plan to catch the edge cases.

Title: Is creating database index part of design, implementation or optimisation process?

Body:
There are a few questions around this subject:

Is creating all indexes at the start (design) over engineering?

In reality, I've added indexes after performance issues were found and we 'explain plan' and add indexes as needed (i.e. not for all relationships). Should I just skip creating indexes before it's needed because performance issues will show up anyway and probably the indexes that's already been created aren't being used?

Should indexes be treated as part of requirement/specification? Sometimes I see performance requirements, which is usually vague or random. If they're part of specification, then should managing indexes be part of implementation?

I want to make it a bit clearer and more background. In development, usually the different phases involve different kinds of people (e.g. architects, seniors and juniors). It'd be unusual for juniors to be responsible for the design, for example. So, when some tasks overlap, it becomes unclear who's responsible if, for example, a query takes 2 second.

Defining development phases and responsibilities are also important for non-programmers, e.g. project managers or product owners, because they are needed for planning and costing. A project manager might want to higher an architect to do all database related task only at the start and for a short time. If after product launch, it's found that performance is poor, the PM would like to know who's responsible. I hope you get the idea.


答:
For sake of discussion, let's be specific in what we mean (and presume you're doing TDD):

Design is the process of specifying the total shape of your system.  You can (and sometimes should) design without directly or indirectly writing a single line of database or program code. You define your Acceptance Tests as the last stage of design.

Implementation is the process of turning said design into a "working" piece of software.  If you're being dogmatic, you wouldn't write a single database index; you'd just define the tables, write the interface object, and rely upon your lower-level platform to load the data.  You write Unit Tests and Integration Tests during the implementation, adn the implementation is done when the Acceptance Tests all pass.

Optimization is making the "working" software you did in Implementation and speeding it up where it runs unacceptably slow.  The three layers of test allow you to make changes without breaking anything.

Of course, that's how it works in theory.  But as a practical matter, since time and money are both limited, you'll often to the steps out of order.  If you expect to need an index on a particular field, there's no reason not to index it as you design it.  If while on a binge of coding you realize how you can elegantly solve an alternate usage situation, you can go ahead and code a draft first and write the unit test second.  (And when you realize your design is wrong, you'll have go to back and revise your tests anyway.)

As to your particular questions:

Is creating all indexes at the start (design) over engineering?

No, if all are useful indexes and they don't take a significant amount of time.

Yes, if you wind up defining indexes for tables that are days away from even the first rough prototype.  (If you create indexes in your initial design, subject them to tests latter on.  They may be more trouble than they're worth.)

Should I just skip creating indexes before it's needed because performance issues will show up anyway and probably the indexes that's already been created aren't being used?

No, if it's clear that you'll need to have some columns indexed.  If you plan on a feature that searches frequently for stock bids over or under a certain price, you'll probably want an index on the bid value in addition to the record's unique key.

Yes, if it's not clear that the index is going to grant the overall system a performance improvement.  The one query a month for bids made by state probably doesn't need a specific index.

Should indexes be treated as part of requirement/specification?

NO.  Indexes are a component of the software design.  They have no more place in requirements or specifications than usage of a particular framework method or transient variable name.

(It's possible for all or part of the programming to come from your customer, but it's foolish to make use of such a requirement.  An index servers no purpose if the server is just going to send the whole table anyway.)


问:
Can classes violate Single Responsibility if they delegate internal tasks?
I have two classes Output and Timeline, neither of which violate SR, but the two of them are linked together. So what I'd like to do is have a class called Elco (there's a reason behind the name) that has both of them as subclasses. For various reasons (this is just a simplified version) it's important that I don't violate the LoD (Law of Demeter). The issue is that technically Elco now has two responsibilities. It delegates those two responsibilities to two classes, which each have one responsibility. Is that not ok? Why? What's a better solution?

答:
Technically speaking, its a little hard to tell whether you are breaking Law of Demeter or not without actually looking at your implementation.

Based on the principle, as long as the object of Elco is directly calling methods of Output and Timeline and not the methods of any other objects that are obtained by Output and Timeline, you are fine.

The problem, however, is that you are coding to an implementation and not abstraction i.e
In your code you will have conditions like:

```<code>if(someCondition)
   call Timeline methods

else
   call Output methods
</code>```

A better approach to this problem would be to define an interface that both Timeline and Output implements. That way, Elco class only has to know about that interface and not about the implementing classes. Your code will then be:

```<code>methodCaller(CommonInterface f) {

      f.interfaceMethod()

}
</code>```

Each of the classes will then provide their own implementations to the method interfaceMethod. This will decouple your code from its implementation, so that in the future you can plugin as many implementations of CommonInterface as you want, without changing the above code.

Body:
Technically speaking, its a little hard to tell whether you are breaking Law of Demeter or not without actually looking at your implementation.

Based on the principle, as long as the object of Elco is directly calling methods of Output and Timeline and not the methods of any other objects that are obtained by Output and Timeline, you are fine.

The problem, however, is that you are coding to an implementation and not abstraction i.e
In your code you will have conditions like:

if(someCondition)
   call Timeline methods

else
   call Output methods

A better approach to this problem would be to define an interface that both Timeline and Output implements. That way, Elco class only has to know about that interface and not about the implementing classes. Your code will then be:

methodCaller(CommonInterface f) {

      f.interfaceMethod()

}

Each of the classes will then provide their own implementations to the method interfaceMethod. This will decouple your code from its implementation, so that in the future you can plugin as many implementations of CommonInterface as you want, without changing the above code.


问:
Security Concerns with password storage in Scripting Languages (VBA)
The team I work with handles large amounts of consumer survey, and internal company metric data. Primarily the data is stored in a database, and we utilize various platforms and to work with that data, including MS Excel.

My peer has developed a suite of Excel/VBA files to take the raw data we get and upload it into a database. Unfortunately, after a code review we identified that the database password was displayed in the VBA code, in plain text, in several places per file. Being in a large enterprise organization we had a number of concerns about those files being available to more than just our team, and the database password being compromised.

The problem is, I feel the solution is just as bad, if not worse than the original problem. The plaintext passwords have been removed in the code of all of the VBA files, and an ancillary, helper file was created that requires the user to authenticate through our organizations LDAP system before gaining access to the database password. Being a scripting language (and being Excel), I feel there really aren't adequate precautions in place to secure the users password in the helper file. I feel that now instead of compromising access to a single database, we are potentially compromising access to the logins of anyone who uses these files.

To be fair, my peer has implemented a number of security minded techniques for securing the data in helper file. I just feel each one can easily be circumvented:

locking the VBA code [google search for vba password recovery]

using a custom "masked" password entry box [the password box may be masked, but it is still passed out of the box as plaintext]

not actually storing the user password in the file itself (he passes it on directly to the LDAP call) [a break point or stop statement can easily reveal the contents of what was passed]

setting the sheets to VeryHidden to prevent direct access [append .zip to filename, and ALL data in ALL worksheets is accessible]

As I'm not one to complain without a solution in mind, our organization already employs Active Directory/LDAP for authentication into our individual machines. My thought is that checking the logged in user (not a full user/password, just the user) against a white list of users on the database should be a sufficient alternative for authentication.

So My Question...

Am I being too paranoid about this? Is there another, more appropriate solution? I am pushing back fairly hard on this fix and I just wanted a sanity check before I start to involve others in yet another solution.

答:
I would not call you paranoid. You are security conscious the steps that your peer has taken do help a bit but they are far from being enough. Still a case can be made about how much security you need.

There is a saying in Security in IT. "Given enough time any system will fall". It's just a matter of balance, how much do you care about that password database and how much is enough security (which also tends to become a burden for the user and developer).

I will say that the techniques you mention are rather weak. If you can see the plain text password then it can probably be sniffed. The code locking seems also very weak, tough I must I admit I know little of this.

Again security is a matter of balancing. What could happen if you password db got compromised?. Balance this with the price of a Security Audit for your solution or hire a security conscious developer that has some experience in the matter.


问:
What must be done to allow a development team to minimize difficulties as new team members are added?
I work at a small Web Dev firm, and have been handling all the PHP/MySQL/etc. for a while. I'm looking at improving our practices to allow for easier collaboration as we grow. Some things I have in mind are:

Implementing a versioning system (source control)

Coding standards for the team (unless
mandated by a certain framework,
etc.)

Enforcing a common directory
structure for our Desktops (for
backup purposes, etc.)

Web-based
task/project/time/file/password/contact
management and collaboration
app(we've tried a bunch; I may just
create one)

What do more experienced developers view as necessary first steps in this area? Do you recommend any books? One thing to consider is that the bulk of our daily tasks involve maintenance and adding minor functionality rather than new projects, and the team size will be between 3 and 5.

I just found a related question about teams that will be expanding from a solo developer.

答:
I think the big thing you've missed there (as the majority of your time is spent maintaining) are unit tests. Since maintenance by default requires modifying existing code, Unit Tests will help you to effectively determine whether or not those changes break anything else.

The other thing I don't see in there is an issue tracking system. Once again, if you're doing a lot of maintenance work, then a good issue tracking system is imperative (though, you may already have either of these, and you just didn't mention them).


问:
Does cohesion really reduce coupling?
'Cohesive classes reduce coupling'

So, if cohesive classes or connected classes reduce coupling (union), which piece of the puzzle is missing me?

BTW, I took this sentence from an article about identifying classes before any developmemt, which I'm trying to figure out the whole sense of why, when, how to use 'that' particular classes, polymorphism, abstraction, etc.

For sure I'm in the beginner stage about OOD. I have read some books but I don't understand the relationship between cohesion and coupling.

答:
It's not contradictory at all.

Cohesion is about how focused the responsibilities of  a given module (or class) are. The more focused, the more cohesive. A class that does only one thing is the most cohesive of all. And it's likely to be coupled to (dependent on) very few other classes, if any.

A class that is less cohesive (in other words, it has more and varied responsibilities) is likely to be coupled to many other classes. Less cohesion, more coupling.

The gist of the 'cohesive classes reduce coupling' phrase is to say that if you build smaller, focused modules, each of them will likely be less coupled than larger, less focused modules. More cohesion allows for more flexibility when composing your modules.

Title: Does cohesion really reduce coupling?


答:
We don't call arrays vectors, either you misunderstood your source or the source misunderstood Java, or both.

An array is a quite different datastructure from a Vector, which is different from a List again (which your pasted code uses).

Of course a mathematical vector could in Java be implemented using either of the three mechanisms, and under the hood either or both the Vector and List might be implemented using arrays.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
I Sure Wish

Yeah... I really do. Having almost a five figure SO-rating, in my geographical area, nobody really cares and finding a new job is quite a daunting task still.

It all boils down to your contact network and experience.


问:
Document Storage Repository - Open Source / Design Pattern
I currently have several web applications that offer document upload and storage.
I am now trying to create a central document management service that these application can leverage to store and retrieve these documents.
Currently the documents are stored on disk. The file name is a Guid and its real file name and datatype are stored in a database.

Am I following the right approach whereby I have a database table that stores the documents information (Name, ContentType, CreatedDate, CreatedBy, SystemId etc), and then store the document in a folder on the local file system of the server ?

When I started storing documents, they were originally blobs in the database. This I found an unfavourable approach. My database was suddenly MASSIVE and impossible to backup and restore. Be separating the documents into the local file system the database is now far simpler and my backup strategy easier. (Backup database, File Diff backup from folder)

Is there a more sensible way to do this I am missing?
Is there some open source project that I can leverage to improve the design of my new service that I am now making from scratch ?

答:
This is probably the best approach.

My only caveat would be that you need to think about backup and error recovery of your document files.

Storing two copies on separate disks would give you roughly the same recoverability as a blob in the database.


问:
Un selectable content using CSS
I have found a website where the text is select protected.

How can i make this without JavaScript. I think it is possible by using CSS.

A set of paragraph is protected with non selectable contents.

But i don't know how to do.

答:
Give Style as

```<code>.unselectable {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
</code>```

In HTML give as

```<code><p class="unselectable">
Your Answer
Thanks for contributing an answer to Programmers Stack Exchange!

Please be sure to answer the question. Provide details and share your research!</p>
</code>```

Now it 'll work.

Title: Un selectable content using CSS

Body:
Give Style as

.unselectable {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}

In HTML give as

<p class="unselectable">
Your Answer
Thanks for contributing an answer to Programmers Stack Exchange!

Please be sure to answer the question. Provide details and share your research!</p>

Now it 'll work.


答:
It is not contradictory; it's actually a pretty basic idea in OOD. Most of OOD principles relate to one another.

Cohesion relates to how well a given functionality is modeled in a system; if that functionality is only implemented in a single module, then that module is highly cohesive. On the other hand, if a certain functionality is scattered among many modules, then those modules have a weak cohesion. As a concrete example on measuring the cohesion of a class, consider a maximum cohesive class one that uses all its instance fields in all the methods. However in practice this is not always achievable nor desirable.

Coupling derives from how many interconnections are between modules and how strong those interconnections are. If modules heavily rely on one another then a change in a module leads to change in multiple modules.

As a relation between them if a functionality is represented by multiple modules (cohesion) then those modules are tightly coupled in order to achieve that functionality. This also relates to Single Responsibility Principle (and many other principles) which states that only one modules should have only one reason to change, leading to the idea that one module should have one functionality.

As OOD reference book I recommend Object Oriented Analysis and Design by Grady Booch et al.

Title: Does cohesion really reduce coupling?

Body:
'Cohesive classes reduce coupling'

So, if cohesive classes or connected classes reduce coupling (union), which piece of the puzzle is missing me?

BTW, I took this sentence from an article about identifying classes before any developmemt, which I'm trying to figure out the whole sense of why, when, how to use 'that' particular classes, polymorphism, abstraction, etc.

For sure I'm in the beginner stage about OOD. I have read some books but I don't understand the relationship between cohesion and coupling.


答:
To answer the question in your title: a class that only delegates to other classes can violate the single-responsibility principle, but does not do so necessarily.

To tell if your Elco class violates the SRP, we would need to know more about its design and the reason you created it.

One dead give-away for breaking the SRP (and in my opinion, also LoD) is if you have a hard time thinking of names for the Elco methods that do not reveal that it is just a thin forwarding wrapper to a similarly names method in Output or Timeline. Such names can be acceptable for a small percentage of the methods, but should raise a red flag if it happens for a significant number of them.

On the other hand, if Elco provides a conceptually higher-level service that can be described in terms of operations on Output and Timeline, then Elco does not violate the SRP and can be seen as an instance of the Facade design pattern.

Title: Can classes violate Single Responsibility if they delegate internal tasks?

Body: I have two classes Output and Timeline, neither of which violate SR, but the two of them are linked together. So what I'd like to do is have a class called Elco (there's a reason behind the name) that has both of them as subclasses. For various reasons (this is just a simplified version) it's important that I don't violate the LoD (Law of Demeter). The issue is that technically Elco now has two responsibilities. It delegates those two responsibilities to two classes, which each have one responsibility. Is that not ok? Why? What's a better solution?


问:
C++11 Header-only Library: in-class body vs. out-class body code?

BACKGROUND:optional

Since 2002 I've been slowly building my own Windows Native C++ library. And let's just say that I have jumped 150KLOC (reusable code) having everything I need and the kitchen sink in it (from most of the Windows API objectualized to a decent IMAP4 client implementation and the WordPress XMLRPC client for mass publishing... I do Affiliate Marketing and SEO Tools). It's not yet .NET but it ain't that far :)

The only 3rd party libraries used in it are ZLib, MySQL and SQLite. Everything else is built from scratch using the STL and/or Windows API. (I still have a PDF writer/reader to implement, IOCP all network things, and there's always room for more work...)

For the past 1.5 years I've been in a sustained effort of updating it for C++11. Move semantics where due, (explicit) bool operators, chained constructs and much more of what (MSVC's modest) C++11 brought us. Plus CRTP for chained parent/child calls, minimal use of virtuals, strict const-correctness. And succeeded.

Recently I've been really considering publishing it. It's a huge amount of work that I've only done for my own benefit and I assume there's still Windows C++ devs out there that could use such a thing. And to do that, went on to read C++ code practices and API/Library design guidelines. It was great! I nailed 80-85% of best coding practices myself. With a few things I'll address soon and one major question.

QUESTION

Currently the entire library is quite-templated and header only. That means all code is in the body of the classes. It's not very easy to manage but it's OK. I collapse code, use #pragma regions and nicely structure things.

BUT I'm VERY tempted, after reading several C++ library coding guidelines, to break it into .hpp + .inl files. Experimentally done so for a few classes and it does increase readability and makes it easier for others to deal with (even if it's a bit harder to write).

I know where everything (line of code, functionality) is at any given time. But other users might want to a quick overview of a classes declaration... and the definition ONLY if/when necessary (debugging).

What are the accepted and/or preferred practices regarding splitting declarations from definitions. Would you rather have header only classes with in-body code or code separated from the function declaration?

What are the current practices of other libraries? I've always written everything myself. Not that up to speed with how others do it. Except the 3 libraries mentioned above, I've yet to use other 3rd party code.

This is an important question for me because it's a one way road. I can't refactor it the other way later on so any feedback matters and is appreciated...

Thanks.

答:
Your question is quite subjective (and might get closed for that), because there is no universally preferred practice when it comes to the use of in-class function definitions in C++.

One project that has a lot of large, header-only, libraries is Boost, and they don't seem to have a defined policy where the body of a method should go.

My personal preference when using a third-party library is (in order of preference)

To have separate, comprehensive, searchable API documentation. This documentation could be generated from the source (for example, with a tool like Doxygen), but I should not have to open the source files myself to read the documentation, or

Well-commented, well-organised class definitions, without the 'clutter' of in-class function bodies. Those implementation details can either come in the same file after the class(es), or in a separate file, or

Well-commented, well-organised class definitions with in-class function bodies.


问:
How would I go about having an editable file to transform an object on a webpage?
I have some code that creates objects on a webpage by using draw on HTML5 canvas.

In my aspx file I have functions like:

```<code>function drawLine(x, y, w, h, width) {
  var canvas = document.getElementById('cpMainContent_myCanvas');
  var ctx = canvas.getContext('2d');
  ctx.moveTo(x, y);
  ctx.lineTo(x + w, y + h);
  ctx.lineWidth = width;
  ctx.stroke();
}
function drawShape(x, y, listOfPoints, fill, width, colour) {
  var canvas = document.getElementById('cpMainContent_myCanvas');
  var ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.moveTo(x, y);
  for (var i = 0; i < listOfPoints.length; i++) {
    ctx.lineTo(listOfPoints[i][0], listOfPoints[i][1]);
  };
  ctx.fillStyle = fill;
  ctx.fill();
  ctx.closePath();
  ctx.lineWidth = width;
  ctx.strokeStyle = colour;
  ctx.stroke();
}
etc...
</code>```

On the server side I generate a string 's' which forms my script and then I call it by using:

```<code>ClientScript.RegisterStartupScript(GetType(), "Test", s.ToString(), true);
</code>```

When the page is displayed it produces something like:

```<code><script type="text/javascript">
//<![CDATA[
function Test(){drawLine(680,409.5,19,0,1);drawSemiCircle(699,409.5,8,0);drawRectangle(700,422.5,68,-26,'#000000',1,'#FFFFFF');drawText('K1D',703,415.5,'14pt Arial Narrow');}Test();//]]>
</script>
</code>```

And I get a web page displaying line drawings depicting certain objects.

My question is, is it possible to have an external file to describe how these objects are created? I have only had a brief look at XSLT and I can't seem to find if it can support bespoke line drawings.

I would like the ability to have a file for each object type, then in the file define what it is made of. E.g. in the file I can declare:
    drawLine(x,y,19,0,1);
    drawSemiCircle(x + 19, y,8,0);

Or something similar.

I think I need to use SVG. The reason I used HTML5 canvas was because I thought this was the latest technology and would do pretty much what SVG does. But it seems to use XSL to create a line drawing on my web page, I would need to use SVG. Am I interpreting this correctly?

答:
You use JavaScript to draw in a canvas. You use declarative XML-markup to create SVG. So if you want to use XSLT, SVG is the only sane choice here.

Some background:

Canvas and SVG are are two completely different approaches to creating dynamic graphics for the web.

The HTML5 canvas element is for drawing bitmap graphics like sprites, games, textures. SVG is for creating vector graphics like charts. Vector graphics can be transformed (scaled/zoomed/rotated) without loosing definition, whereas bitmap images cannot.


问:
Programming structural question, controlling lots of states and specific transitions between states case by case
This is a theory question for me just to try and write better code. I am pretty new so hopefully I am using terms like state in the correct way.

How I should be thinking about this problem? I am coding something that sort of works but whatever I do it seems complicated, hard to understand and hard to modify.

I'm playing a video clip with an id, I also want it to be able to dynamically switch to a thumbnail view of that video clip. I want to be able to set this video blank also and shut down any connections that are not needed, I'm trying to do all of this efficiently - not reconnecting to the server when I don't need to etc.

so I have-

connected -> on/off

video id -> a string

mode -> streaming video/thumbnail view/disabled

Hopefully you will see my dilemma with some examples-

Case 1.The user starts from scratch and wants to view a thumbnail of video "a"

-connect to server for "a", send request for thumbnail, turn thumbnail object on.

Case 2.The user starts is viewing a thumbnail of video "a" and wants to start watching a stream of video "b"

-compare strings "a" and "b"- see they are different. hide thumbnail object and clear its buffer. Disconnect from server for "a" and connect to "b" server. start streaming video, turn video object on, request thumbnail from the server so its loaded in memory in case the user wants to switch to thumbnail mode.

Case 3.the user is watching a stream of "b" and wants to view a thumbnail of "b"

-compare strings "b" and "b"- see they are the same and stay connected to the server, hide video object and stop streaming, turn thumbnail object on, send another request to server for the thumbnail...

All these options are doing my head in, I want it to choose the most efficient way to get from one state to another but all the different options are confusing me. I guess Im looking for help about whats the best way to structure this, because what Im doing at the moment seems very confusing, i end up with huge tree of nested ifs of lots of specific cases and then patching up where it goes wrong.

```<code>if (connected but used to be disconnected) {
    if (mode streaming but used to be thumbnail) {...
    if (mode streaming but used to be streaming) {...

if (connected but used to be connected) {....

if (disconnected but used to be connected) {....

if (disconnected but used to be disconnected) {...
</code>```

it goes on forever..

答:
Encapsulate each non-trivial state in a separate State class which knows how to transition from one state to the next. When a transition occurs, the state object changes. For instance, from "ConnectedState" to "DisconnectedState".

Model your problem as a state machine. I'm a big fan of the state pattern to solve these things.


问:
Additional class for objects construction when working with database
I have a class derived from SQLiteOpenHelper which is all about working with a database, i.e. tables creation, insertions, data selections. All methods which deal with data selection return a Cursor. What I really want is to get a list of objects rather than a cursor, at the same time I don't want my class to do a lot of things. Is it a good idea to add another class who get selections from a database and construct objects from the selection? Thank you.

答:
One pattern you should look into is the Repository pattern. Nice example here. There will be many others out there on the web.

The Repository pattern compliments your database access and  allows you to define queries and return result items as the objects you want.

You create your domain object like User and return that object type from the repository.


答:
There is one major and some minor technical differences between body inside the class and outside of it.

The major difference is that method with body inside the class is implicitly considered declared inline. Not that compilers don't inline whatever they want anyway, but it affects the code generation somewhat. It is likely that if you overdo it with inline methods, the binary will be bigger and a little slower, so there is an argument for not writing larger bodies inside the class.

There is at least one minor difference; the only way to define a friend function (e.g. operator) for inner class of class template is with body inside the class. The friend modifier makes it not a member.

Title: C++11 Header-only Library: in-class body vs. out-class body code?

Body:
BACKGROUND:optional

Since 2002 I've been slowly building my own Windows Native C++ library. And let's just say that I have jumped 150KLOC (reusable code) having everything I need and the kitchen sink in it (from most of the Windows API objectualized to a decent IMAP4 client implementation and the WordPress XMLRPC client for mass publishing... I do Affiliate Marketing and SEO Tools). It's not yet .NET but it ain't that far :)

The only 3rd party libraries used in it are ZLib, MySQL and SQLite. Everything else is built from scratch using the STL and/or Windows API. (I still have a PDF writer/reader to implement, IOCP all network things, and there's always room for more work...)

For the past 1.5 years I've been in a sustained effort of updating it for C++11. Move semantics where due, (explicit) bool operators, chained constructs and much more of what (MSVC's modest) C++11 brought us. Plus CRTP for chained parent/child calls, minimal use of virtuals, strict const-correctness. And succeeded.

Recently I've been really considering publishing it. It's a huge amount of work that I've only done for my own benefit and I assume there's still Windows C++ devs out there that could use such a thing. And to do that, went on to read C++ code practices and API/Library design guidelines. It was great! I nailed 80-85% of best coding practices myself. With a few things I'll address soon and one major question.

QUESTION

Currently the entire library is quite-templated and header only. That means all code is in the body of the classes. It's not very easy to manage but it's OK. I collapse code, use #pragma regions and nicely structure things.

BUT I'm VERY tempted, after reading several C++ library coding guidelines, to break it into .hpp + .inl files. Experimentally done so for a few classes and it does increase readability and makes it easier for others to deal with (even if it's a bit harder to write).

I know where everything (line of code, functionality) is at any given time. But other users might want to a quick overview of a classes declaration... and the definition ONLY if/when necessary (debugging).

What are the accepted and/or preferred practices regarding splitting declarations from definitions. Would you rather have header only classes with in-body code or code separated from the function declaration?

What are the current practices of other libraries? I've always written everything myself. Not that up to speed with how others do it. Except the 3 libraries mentioned above, I've yet to use other 3rd party code.

This is an important question for me because it's a one way road. I can't refactor it the other way later on so any feedback matters and is appreciated...

Thanks.


答: The answers above describe why this class is different from an "Array" - and I suspect the reason a different name is used is because programmers are helped by having a well organised namespace - in other words if you talk about a "Vector" it is clear precisely what class you mean, while if all similar classes were merely arrays then it would not be fully clear.</p>


问:
Trying to understand the 2N lnN compares for quicksort
I was going through the analysis of quicksort in  Sedgewick's Algorithms book. He creates the following recurrence relation for number of compares in quicksort while sorting an array of N distinct items.

I am having a tough time understanding this... I know it takes 1/N probability for any element to become the pivot and that if k becomes the pivot, then the left sub-array will have k-1 elements and right sub-array will have N-k elements.

1.How does the cost of partitioning become N+1 ? Does it take N+1 compares to do the partitioning?

2.Sedgewick says, for each value of k, if you add those up, the probability that the partitioning element is k + the cost for the two sub-arrays you get the above equation.

Can someone explain this so that those with less math knowledge (me) can understand?

Specifically how do you get the second term in the equation?

What exactly does that term stand for?

答:
It seems that N+1 as the number of comparisons for the partition step is an error in the book. You need to find out for each of the N–1 non-pivot elements whether it is less than or greater than the pivot, which takes one comparison; thus N–1 comparisons in total, not N+1. (Consider the simplest case, N=2, i.e. one pivot and one other element: There is absolutely no room for doing three comparisons between two elements.)

Consider the case where the chosen pivot happens to be the smallest element (k=1). This means that the array is divided into an empty part to the left (there are no elements that are less than the pivot) and a part to the right that contains all the elements except for the pivot (all other elements are greater than the pivot). This means that the sub-problems that you now want to solve recursively have sizes 0 and N–1 (k–1 and N–k), respectively, and require C(0) and C(N–1) comparisons; thus, C(0)+C(N–1) in total.

If the pivot happens to be the second smallest element (k=2), the sub-problem sizes are 1 and N–2 (k–1 and N–k; one element on the left, because it is the only one smaller than the pivot). Thus, recursively solving these sub-problems requires C(1)+C(N–2) comparisons. And so on if the pivot is the third smallest element, the fourth, etc. These are the expressions in the numerators.

Because the pivot is chosen randomly from among the N elements, each case (pivot is smallest, pivot is second smallest, etc.) occurs with equal probability 1/N. That’s where the N in the denominators comes from.


答: RAM is most important but you also look at things like using a CDN for scripts on your site such as jQuery to remove the load from your server serving them and make sure everything (css/javascript/images) is compressed as much as possible.</p>

Title: What aspects make websites load faster?


问:
How much time can I spend learning at work?
I've been working as a software developer for about 2 years by now. It seems obvious that in a field so rapidly evolving as software development, you need to spend time on learning new technologies, frameworks, etc.

I always thought I could take it for granted that if I need to learn something to solve a problem at work, I am free to spend the hours needed learning that at work as well. However, I have had discussions about this topic with various colleagues, and we were holding very different opinions, apparently on the span of two extremes:

Your employer pays you for knowing stuff. You got hired for having knowledge on the field of expertise required for doing this job, and if the field emerges so that you need to aquire more knowledge, it is only natural that you do so in your free time.

And the other extreme being

Whatever makes me more productive at work in the long run, is worth spending the time on at work, because the employer will eventually profit from that. This does of course apply to learning new techniques, but also, e.g. learning VIM to get faster, etc.

But even when discussing how long to spend time on something with the guys tending to the second extreme, we were of vastly different opinions, ranging from "an hour every now and then is okay" to "however long it takes".

Does your workplace encourage learning new skills and if so what processes do they have to encourage this? How much time do you spend learning new things (and not writing production code) during your day as a programmer?

答:
I tend to just plan some extra time for my projects in order to get some learning done.
I also see spending time on sites like Stackoverflow etc. as learning new stuff for a certain task.

I couldn't put my finger on an hour a day or rules like that. Just some days are very productive and highly efficient and other days I just hit the books or read up on stuff. Mostly the 'learning days' fall into my planning stage of new projects.

Also I have a long commute to work where I read up on stuff.

Basically just try and find out what suits you best without feeling guilty or just wasting time at work. As long as you can explain and justify time spent not programming you should be fine in most cases. I think every developer or engineer should know quite a bit regarding their field of expertise and especially know where to find deeper knowledge when needed.


答:
Learning at work falls into 3 main categories:

training the employer explicitly trains you on, eg training courses.

training you get as part of your job, eg the employer requires you to learn technology or product (this includes internal technologies and products) and allocates you some time with internal mentors/trainers.

everything else you can get away with, eg time spent surfing SO or other tech sites, reading up about technologies.

number 3 is far and away the most common - if you can get away with learning something new on company time, without the boss noticing, then go for it. Just be aware that personal improvement is almost never a part of your contractual employment. You get paid to produce products for your employer, not to train yourself. Welcome to the world of being a wage slave :-)

Title: How much time can I spend learning at work?

Body:
I've been working as a software developer for about 2 years by now. It seems obvious that in a field so rapidly evolving as software development, you need to spend time on learning new technologies, frameworks, etc.

I always thought I could take it for granted that if I need to learn something to solve a problem at work, I am free to spend the hours needed learning that at work as well. However, I have had discussions about this topic with various colleagues, and we were holding very different opinions, apparently on the span of two extremes:

Your employer pays you for knowing stuff. You got hired for having knowledge on the field of expertise required for doing this job, and if the field emerges so that you need to aquire more knowledge, it is only natural that you do so in your free time.

And the other extreme being

Whatever makes me more productive at work in the long run, is worth spending the time on at work, because the employer will eventually profit from that. This does of course apply to learning new techniques, but also, e.g. learning VIM to get faster, etc.

But even when discussing how long to spend time on something with the guys tending to the second extreme, we were of vastly different opinions, ranging from "an hour every now and then is okay" to "however long it takes".

Does your workplace encourage learning new skills and if so what processes do they have to encourage this? How much time do you spend learning new things (and not writing production code) during your day as a programmer?


问:
How can I combine C/Fortran with JavaScript?
I'm working on a project where I need heavy numerical calculations to be real-time visualized with something flexible like D3.js. Are there frameworks out there that would let me painlessly achieve this? Or do I need to use some sort of "glue" code written in, say, Python?</p>

答:
Write a CGI, make an HTTP server and a browser do the rest.

If you need more performance later, you can turn it into a FastCGI.

If you (your bosses) are really that desperate into making it look like there isn't a browser doing the heavy hauling, look into including a WebKit widget (cross platform) or embedding an MSIE frame (all-around easier and faster, but only available on Windows, and might raise issue with MSIE versions) into your windowed app.


答:
The problem with doing stuff in your free time is that you need to actually have some free time. Try being a father with a young baby! Try working 14 hours a day and then find time. Taking time to learn new skills needs to balanced with time to relax and re-charge. Also I find that having time to relax helps me solve problems at work. I quite often find solutions when doing the washing up!

At previous firms I introduced the idea of a trade. The company provided an hour a week for us to learn and we matched it with an hour of our own time. Sensible firms should welcome the opportunity for its employees to learn new skills. At the same firm other programmers introduced the idea of 'brown bag' sessions, where we would spend a lunch-hour getting an introduction to new ideas and skills.


答:
Depending on the size of your enterprise, as the demands of your content management system increase, you may need multiple instances and so your architecture should be designed in such a way as to target not only a document id, but the content management instance id for which it resides.

The service users should not have to worry about this routing detail, however. Architect a solution where you have some sort of rules engine that figures out the best instance to use to store the document. It could be based on some sort of statistics gathering or monitoring process (perhaps some other scheme altogether) so that the most efficient routing path is used.

The point is that this "routing system" is decoupled from both the content management system instance AND the clients who use them, allowing you to maintain your routing scheme without too much disruption to either the users or the content management system instances.

As the document management process runs over an extended period of time, you will have a better feel about what rules to apply for routing, possibly changing your rules engine.

Your guid would be thus created by your routing system, not the content management system (for example docid + ":" + instanceid). The routing system database that stores metadata should have sufficient information that can be used to support future changes to rules engine (to make it work even more efficiently)

Title: Document Storage Repository - Open Source / Design Pattern

Body:
I currently have several web applications that offer document upload and storage.
I am now trying to create a central document management service that these application can leverage to store and retrieve these documents.
Currently the documents are stored on disk. The file name is a Guid and its real file name and datatype are stored in a database.

Am I following the right approach whereby I have a database table that stores the documents information (Name, ContentType, CreatedDate, CreatedBy, SystemId etc), and then store the document in a folder on the local file system of the server ?

When I started storing documents, they were originally blobs in the database. This I found an unfavourable approach. My database was suddenly MASSIVE and impossible to backup and restore. Be separating the documents into the local file system the database is now far simpler and my backup strategy easier. (Backup database, File Diff backup from folder)

Is there a more sensible way to do this I am missing?
Is there some open source project that I can leverage to improve the design of my new service that I am now making from scratch ?


答:
The cost function C for quicksort consists of two parts. The first part is the cost of partitioning the array in two 'halves' (the halves don't have to be of equal size, hence the quotes). The second part is the cost of sorting those two halves.

The (N + 1) term is actually a condensed term, and comes from the terms

```<code>(N - 1) + 2
</code>```

This is the cost of the partitioning in quicksort: N-1 compares with the pivot value, and 2 additional compares due to some boundary conditions in the partitioning.

The second part of the equation consists of the costs for sorting the two 'halves' on either side of the pivot value k.

After choosing a pivot value, you are left with two unsorted 'halves'. The cost of sorting these 'halves' depends on their size and is easiest described as a recursive application of the cost function C. If the pivot is the smallest of the N values, the costs for sorting each of the two 'halves' is respectively C(0) and C(N-1) (the cost for sorting an array with 0 elements and the cost for sorting one with N-1 elements).
If the pivot is the fifth-smallest, then the cost for sorting each of the two 'halves' is respectively C(5) and C(N-6) (the cost for sorting an array with 5 elements and the cost for sorting one with N-6 elements). And similarly for all other pivot values.

But how much does it cost to sort those two 'halves' if you don't know the pivot value? This is done by taking the cost for each possible value of the pivot and multiplying that by the chance that that particular value turns up.

As each pivot value is equally likely, the chance for choosing a particular pivot value is 1/N if you have N elements. To understand this, think about rolling a dice. With a proper dice, the chance for each side to end up facing up is equal, so the chance to roll a 1 is 1/6.

Combined, this gives the summation term where, for each possible value k of the pivot, the cost (C(k-1) + C(N-k)) is multiplied by the chance (1/N)

The further derivation of the summation formulat in the question to the 2N lnN in the title takes too much math to explain herein detail, but it is based on the understanding that the cost for sorting an array of N elements (C(N)) can be expressed in terms of sorting an array of N-1 elements (C(N-1)) and a factor that is directly proportional to N.

Title: Trying to understand the 2N lnN compares for quicksort

Body:
I was going through the analysis of quicksort in  Sedgewick's Algorithms book. He creates the following recurrence relation for number of compares in quicksort while sorting an array of N distinct items.

I am having a tough time understanding this... I know it takes 1/N probability for any element to become the pivot and that if k becomes the pivot, then the left sub-array will have k-1 elements and right sub-array will have N-k elements.

1.How does the cost of partitioning become N+1 ? Does it take N+1 compares to do the partitioning?

2.Sedgewick says, for each value of k, if you add those up, the probability that the partitioning element is k + the cost for the two sub-arrays you get the above equation.

Can someone explain this so that those with less math knowledge (me) can understand?

Specifically how do you get the second term in the equation?

What exactly does that term stand for?

Body:
The cost function C for quicksort consists of two parts. The first part is the cost of partitioning the array in two 'halves' (the halves don't have to be of equal size, hence the quotes). The second part is the cost of sorting those two halves.

The (N + 1) term is actually a condensed term, and comes from the terms

(N - 1) + 2

This is the cost of the partitioning in quicksort: N-1 compares with the pivot value, and 2 additional compares due to some boundary conditions in the partitioning.

The second part of the equation consists of the costs for sorting the two 'halves' on either side of the pivot value k.

After choosing a pivot value, you are left with two unsorted 'halves'. The cost of sorting these 'halves' depends on their size and is easiest described as a recursive application of the cost function C. If the pivot is the smallest of the N values, the costs for sorting each of the two 'halves' is respectively C(0) and C(N-1) (the cost for sorting an array with 0 elements and the cost for sorting one with N-1 elements).
If the pivot is the fifth-smallest, then the cost for sorting each of the two 'halves' is respectively C(5) and C(N-6) (the cost for sorting an array with 5 elements and the cost for sorting one with N-6 elements). And similarly for all other pivot values.

But how much does it cost to sort those two 'halves' if you don't know the pivot value? This is done by taking the cost for each possible value of the pivot and multiplying that by the chance that that particular value turns up.

As each pivot value is equally likely, the chance for choosing a particular pivot value is 1/N if you have N elements. To understand this, think about rolling a dice. With a proper dice, the chance for each side to end up facing up is equal, so the chance to roll a 1 is 1/6.

Combined, this gives the summation term where, for each possible value k of the pivot, the cost (C(k-1) + C(N-k)) is multiplied by the chance (1/N)

The further derivation of the summation formulat in the question to the 2N lnN in the title takes too much math to explain herein detail, but it is based on the understanding that the cost for sorting an array of N elements (C(N)) can be expressed in terms of sorting an array of N-1 elements (C(N-1)) and a factor that is directly proportional to N.


答:
I know some people in the office that have been researching new technologies for years now.

Yet they haven't presented something new, I guess as in everything, people tend to abuse,

And where there is abuse, there is control measurement.


答:
Managers (like me) are hesitant to specify explicit training budgets. According to Parkinson's Law, such a budget would be consumed or even exhausted regardless of the actual needs in knowledge development.

If you just call your learning time project work and keep it in reasonable proportion to your overall work and your overall achievements, nobody will object. The percentage varies and depends on your age, experience and working area. I would regard between two and 15 days of training per year as normal. New employees often need more.

In a very innovative environment, the learning and researching percentage is typically higher than usual. We have a mentoring scheme for junior developers. Whenever somebody changes his/her working area, additional training is obviously required.

The learning issue is a matter of self marketing. No team would tolerate a member who is constantly unavailable due to demonstrative self-study or extensive absence in exotic training courses. Try to appear well-informed without utilizing excessive resources for your learning. The project time needed to experiment and learn is mostly treated discretely. Would you personally pay a craftsman for getting to know your brand of car?

For knowledge-deficiencies which are in contrast to your job description, private engagement would be taken for granted. Example: If you are supposed to be a Senior Java Developer, you should not ask for a basic Java training.


问:
How are the size of the stack and heap limited by the OS?
Note: if you need to consider a specific OS to be able to answer, please consider Linux.

Whenever I run a program, it will be given a virtual memory space to run in, with an area for its stack and one for its heap.

Question 1: do the stack and the heap have a static size limit (e.g., 2 gigabytes each), or is this limit dynamic, changing according to the memory allocations during the execution of the program (i.e., 4 gigabytes total to be used by both, so if a program only uses the stack, it will be able to have a stack with 4 gigabytes)?

Question 2: How is the limit defined? Is it the total available RAM memory?

Question 3: What about the text (code) and data sections, how are they limited?

答:
There are two different memory limits. The virtual memory limit and the physical memory limit.

Virtual Memory

The virtual memory is limited by size and layout of address space available. Usually at the very beginning is the executable code and static data and past that grows the heap, while at the end is area reserved by kernel, before it the shared libraries and stack (which on most platforms grows down). That gives heap and stack free space to grow, the other areas being known at process startup and fixed.

The free virtual memory is not initially marked as usable, but is marked such during allocation. While heap can grow to all available memory, most systems don't auto-grow stacks. IIRC default limit for stack is 8MiB on Linux and 1MiB on Windows and can be changed on both systems. The virtual memory also contains any memory-mapped files and hardware.

One reason why stack can't be auto-grown (arbitrarily) is that multi-threaded programs need separate stack for each thread, so they would eventually get in each other's way.

On 32-bit platforms the total amount of virtual memory is 4GiB, both Linux and Windows normally reserving last 1GiB for kernel, giving you at most 3GiB of address space. There is a special version of Linux that does not reserve anything giving you full 4GiB. It is useful for the rare case of large databases where the last 1GiB saves the day, but for regular use it is slightly slower due to the additional page table reloads.

On 64-bit platforms the virtual memory is 64EiB and you don't have to think about it.

Physical Memory

Physical memory is usually only allocated by the operating system when the process needs to access it. How much physical memory a process is using is very fuzzy number, because some memory is shared between processes (the code, shared libraries and any other mapped files), data from files are loaded into memory on demand and discarded when there is memory shortage and "anonymous" memory (the one not backed by files) may be swapped.

On Linux what happens when you run out of physical memory depends on the vm.overcommit_memory system setting. The default is to overcommit. When you ask the system to allocate memory, it gives some to you, but only allocates the virtual memory. When you actually access the memory, it will try to get some physical memory to use, discarding data that can be reread or swapping things out as necessary. If it finds it can't free up anything, it will simply remove the process from existence (there is no way to react, because that reaction could require more memory and that would lead to endless loop).

This is how processes die on Android (which is also Linux). The logic was improved with logic which process to remove from existence based on what the process is doing and how old it is. Than android processes simply stop doing anything, but sit in the background and the "out of memory killer" will kill them when it needs memory for new ones.


问:
How do you put a price on your source code?
I was asked to sell the source code (along with existing users) of small utility app I created years ago. I've investigated how to put a price on the source code but so far haven't come up with a good solution.

I've searched the net, but haven't found anything useful. Then I came across a few others who also sold their source code with users, but their prices seem unrealistically high. For example, one person calculated price per user at about $200. He had 80 users and ended up selling the source with users for $30k. How did he come up with this price?

Can I find a good price with this formula:

(number of users x app price) + (app price x num of new users in one year)

?

If this is a good formula, how do you price source that doesn't yet have users?

答:
The value of the source code is not necessarily related to the cost to produce it.

The real value is a percentage of the value to the entity which intends to purchase the source code.

If the source code produces $75,000 in value for a business, the cost could be a percentage of $75,000. Maybe $15,000 to $30,000+ depending on your negotiating skills.


问:
Is PGM (Pragmatic General Multicast) viable to achieve reliable message delivery with IP multicast?
I have a server application that distributes stock quotes to a number of clients on our internal network. As the number of clients has grown, unicast (TCP) connections between the server and the clients do not scale anymore. Hence, I have been looking into multicasts.

Because of the inherent unreliability of IP multicast, I have been looking into reliable multicast and found Pragmatic General Multicast (PGM). Things like NAK suppression, forward error correction etc. sound like just the things I need and would have to implement myself when using raw UDP.

Before I convert a mission critical application to this protocol, there are a couple of questions:

How widely used is PGM? There aren’t many hits for it on Stack Overflow, Server Fault or the new Network Engineering Stack Exchange site. The RFC  is from 2001 and a paper on the Microsoft Research site is from 2003. Why hasn’t this been adopted as a standard already?

How viable is the Microsoft implementation of PGM? The documentation is extremely sparse and most projects using PGM (e.g. zeroMQ) seem to be built on top of OpenPGM. But using a socket API that comes with the operating system and that I am already familiar and that has good support in Delphi and C# (the languages I use) seems better than having to rely on additional libraries that need to be built separately and have their own dependencies. Are there any drawbacks of MS-PGM that I should be aware of?

What are the alternatives? Are there other protocols that bring reliability to multicast programming, but e.g. allow for reordering of packets? That wouldn’t be a problem but actually a feature, because it would allow me to continue processing some instruments even when packets for others have been lost.

答:
I would argue that you're looking at too low of a level. You should be looking at message queues like ZeroMQ or others  to build what's known as a service bus. ZeroMQ and most other message queue systems have client libraries for most popular languages and platforms. The connections are feather-light and scale highly. The message queues also support concepts like channels which allows clients to "subscribe" to topics that only interest them (eg particular stock tickers and the like). This capability known as Pub-Sub helps minimize network traffic over raw multicast in that messages are only delivered to those clients subscribing to a topic.

Hope this helps.


问:
Strategy with using SVN to switch between test and production server. (with maintaining configuration files)
I would like to know your opinion about my setup right now, how I do things with SVN and if you could find some better solution for me. I'd appreciate it very much if someone could come up with some better solutions for my problems. I would like to do it the best way possible and the most efficiently.

My situation is as follows:
I'm maintaining a PHP website which is connected to mysql database. I have a subdomain on which I'm testing everything. There are also two databases: first for testing purposes, second for the production server.
I have a project in Netbeans and I'm connected to ftp with it so every change I make is directly transferred to the website. Also I'm connected to SVN server and the testing part of the website is in trunk directory. Every time I want to upload the changes to the server I'm commiting my trunk and then I'm copying it to tags. After that I got another project in Netbeans prepared, already connected to the same SVN, but to the last tag copy. After I copy the trunk to tag directory, I switch to the second project and switch to the newest version in tags. Now I have in some another directory every configuration file prepared in proper directory structure - I copy it to my production project. After that I click "Run" in Netbeans and that opens a window which allows me to accept the transfers to the sftp, but this time to the production part of the website.

My question is: is it the best way? Aren't there any more intuitive tools or options in SVN, so I don't have to copy the configuration files every time?

答: A simple solution would be to keep all the configuration files in the repo and the have a build script that copies the correct version for the environment in when needed. </p>


答:
A software package has two kinds of configuration:

environment-specific configuration

behaviour-specific configuration

The former differs between the devel, test, stage and production environments. It should have at most 4 lines or so (web server base url, database connection string, SSL certificates, connection strings/urls to other related components, installation directory, authentication realm and such; you rarely need most of those even) and since it makes absolutely zero sense outside this installation on the particular server (i.e. it may change when the server is reinstalled), it should generally not be versioned (except as part of versioning the server installation if your admin is into that).

The later should be versioned all right, but must not differ between the environments. It's just part of the source/build.

Obviously the configuration needs to be appopriately split across two files so you can version the one you need and not the other one.

Title: Strategy with using SVN to switch between test and production server. (with maintaining configuration files)

Body:
I would like to know your opinion about my setup right now, how I do things with SVN and if you could find some better solution for me. I'd appreciate it very much if someone could come up with some better solutions for my problems. I would like to do it the best way possible and the most efficiently.

My situation is as follows:
I'm maintaining a PHP website which is connected to mysql database. I have a subdomain on which I'm testing everything. There are also two databases: first for testing purposes, second for the production server.
I have a project in Netbeans and I'm connected to ftp with it so every change I make is directly transferred to the website. Also I'm connected to SVN server and the testing part of the website is in trunk directory. Every time I want to upload the changes to the server I'm commiting my trunk and then I'm copying it to tags. After that I got another project in Netbeans prepared, already connected to the same SVN, but to the last tag copy. After I copy the trunk to tag directory, I switch to the second project and switch to the newest version in tags. Now I have in some another directory every configuration file prepared in proper directory structure - I copy it to my production project. After that I click "Run" in Netbeans and that opens a window which allows me to accept the transfers to the sftp, but this time to the production part of the website.

My question is: is it the best way? Aren't there any more intuitive tools or options in SVN, so I don't have to copy the configuration files every time?


答:
In my previous webdev job, we were 5 devs working.

We've succesfully used redmine issue tracking software to maintain and create new projects, it supported subversion and mercurial as version control system (VCS); in tandem. So projects were not prohibited to use different VCS than the rest. The only thing that matters is that you keep track of your issue numbers and redmine does the rest.

Coding standards grows out of necessity. When the team starts to have merge conflicts, they tend to set standards among themselves to avoid the conflicts. It's a good learning experience.

I'm puzzled with the common directory structure thing. Web devs usually are good at wiping their computers clean and set up the computer quickly again. If you have problems setting up the computer again, you really should version control the web configurations so your projects are already set up when you check out the code.

Title: What must be done to allow a development team to minimize difficulties as new team members are added?

Body:
I work at a small Web Dev firm, and have been handling all the PHP/MySQL/etc. for a while. I'm looking at improving our practices to allow for easier collaboration as we grow. Some things I have in mind are:

Implementing a versioning system (source control)

Coding standards for the team (unless
mandated by a certain framework,
etc.)

Enforcing a common directory
structure for our Desktops (for
backup purposes, etc.)

Web-based
task/project/time/file/password/contact
management and collaboration
app(we've tried a bunch; I may just
create one)

What do more experienced developers view as necessary first steps in this area? Do you recommend any books? One thing to consider is that the bulk of our daily tasks involve maintenance and adding minor functionality rather than new projects, and the team size will be between 3 and 5.

I just found a related question about teams that will be expanding from a solo developer.


答:
I think it's easier to answer this by the order of how the memory is used.

Question 3: What about the text (code) and data sections, how are they limited?
Text and Data are prepared by the compiler. The requirement for the compiler is to make sure that they are accessible and pack them in the lower portion of address space. The accessible address space will be limited by the hardware, e.g. if the instruction pointer register is 32-bit, then text address space would be 4 GiB.

Question 2: How is the limit defined? Is it the total available RAM memory?
After text and data, the area above that is the heap. With virtual memory, the heap can practically grow up close to the max address space.

Question 1: do the stack and the heap have a static size limit (e.g., 2 gigabytes each), or is this limit dynamic, changing according to the memory allocations during the execution of the program (i.e., 4 gigabytes total to be used by both, so if a program only uses the stack, it will be able to have a stack with 4 gigabytes)?
The final segment in the process address space is the stack. The stack takes the end segment of the address space and it starts from the end and grows down.

Because the heap grows up and the stack grows down, they basically limit each other. Also, because both type of segments are writeable, it wasn't always a violation for one of them to cross the boundary, so you could have buffer or stack overflow. Now there are mechanism to stop them from happening.

There is a set limit for heap (stack) for each process to start with. This limit can be changed at runtime (using brk()/sbrk()). Basically what happens is when the process needs more heap space and it has run out of allocated space, the standard library will issue the call to the OS. The OS will allocate a page, which usually will be manage by user library for the program to use. I.e. if the program wants 1 KiB, the OS will give additional 4 KiB and the library will give 1 KiB to the program and have 3 KiB left for use when the program ask for more next time.

Most of the time the layout will be Text, Data, Heap (grows up), unallocated space and finally Stack (grows down). They all share the same address space.

Title: How are the size of the stack and heap limited by the OS?

Body:
Note: if you need to consider a specific OS to be able to answer, please consider Linux.

Whenever I run a program, it will be given a virtual memory space to run in, with an area for its stack and one for its heap.

Question 1: do the stack and the heap have a static size limit (e.g., 2 gigabytes each), or is this limit dynamic, changing according to the memory allocations during the execution of the program (i.e., 4 gigabytes total to be used by both, so if a program only uses the stack, it will be able to have a stack with 4 gigabytes)?

Question 2: How is the limit defined? Is it the total available RAM memory?

Question 3: What about the text (code) and data sections, how are they limited?


问:
Writing Tests for Existing Code
Suppose one had a relatively large program (say 900k SLOC in C#), all commented/documented thoroughly, well organized and working well. The entire code base was written by a single senior developer who no longer with the company. All the code is testable as is and IoC is used throughout--except for some strange reason they did not write any unit tests. Now, your company wants to branch the code and wants unit tests added to detect when changes break the core functionality.

Is adding tests a good idea?

If so, how would one even start on something like this?

EDIT

OK, so I had not expected answers making good arguments for opposite conclusions. The issue may be out of my hands anyway. I've read through the "duplicate questions" as well and the general consensus is that "writing tests is good"...yeah, but not too helpful in this particular case.

I don't think I am alone here in contemplating writing tests for a legacy system. I'm going to keep metrics on how much time is spent and how many times the new tests catch problems (and how many times they don't). I'll come back and update this a year or so from now with my results.

CONCLUSION

So it turns out that it is basically impossible to just add unit test to existing code with any semblance of orthodoxy. Once the code is working you obviously cannot red-light/green-light your tests, it usually not clear which behaviors are important to test, not clear where to begin and certainly not clear when you are finished. Really even asking this question misses the main point of writing tests in the first place. In the majority of cases I found it actually easier to re-write the code using TDD than to decipher the intended functions and  retroactively add in unit tests. When fixing a problem or adding a new feature it is a different story, and I believe that this is the time to add unit tests (as some pointed out below). Eventually most code gets rewritten, often sooner than you'd expect--taking this approach I've been able to add test coverage to a surprisingly large chunk of the existing codebase.

答:
Yes, having tests is a good idea. They will help document the existing codebase works as intended and catch any unexpected behaviour. Even if the tests initially fail, let them, and then refactor the code later so that they pass and behave as intended.

Start writing tests for smaller classes (ones that have no dependencies and are relatively simple) and move on to larger classes (ones that have dependencies and are more complex). It will take a long time, but be patient and persistent so that you can eventually cover the codebase as much as possible.

Title: Writing Tests for Existing Code