问:
Are design patterns really essential nowadays?
I was reading "Coders at Work" and have faced the fact that some of the professionals interviewed in the book are not so enthusiastic about design patterns.

I think that there are 2 main reasons for this:

Design patterns force us to think in their terms. In other words, it's almost impossible to invent something new (maybe better).

Design patterns don't last forever. Languages and technologies change fast; therefore, design patterns will eventually become irrelevant.

So maybe it's more important to learn how to program properly without any particular patterns and not to learn them.

The point also was that usually when people face a problem and they don't have much time, they try to use a pattern. This means copying and pasting existing code into your project with minor changes in order to get it working. When it's time to change or add something, a developer doesn't know where to start because it's not his code and he's not deeply familiar with it.

答: Slavish adherence to design patterns can be detrimental - patterns are documented solutions to common problems, but they are not instruction manuals. However, just because they are discussed at length and, in some cases, applied outside of effective problem domains doesn't mean they hold no value whatsoever. They are a set of principles - call it a framework - to draw upon when designing a program's architecture, allowing for the architect to give an impression of how he/she would like to see the solution work. A good development team views them as a basis for functionality, rather than a functional specification.</p>


问:
Reverse relationships for smaller/better Aggregates?
Let's take an example: we have two related entities, like Question and Choice. This is a poll: it contains of single question that may have 2 or more choices. Each choice can be voted for by users, each vote is stored.

Obviously, on paper, Question would contain a collection of Choices. And probably we would have something like this:

```<code>public class Question {
    List<Choice> choices;
    public void assignChoice(Choice choice) {}
    public List<Choice> getChoices();
}
</code>```

Question is an Aggregate that contains list of other entity, Choice.

Now, if the Choice is a value object, I would be fine. Repository should store the aggregate starting from root, so it would store a root entity and related value objects.

However, here we have aggregate of entities! In that sense I wonder: why do we need to maintain collection in Question at all? I mean, for view, we will have query read-only model. For commands we might not needed it at all.

So we can move from this:

```<code>Question question = new Question("Favorite color?");
question.assignAnswer(new Choice("red"));
question.assignAnswer(new Choice("blue"));

questionRepository.store(question);
</code>```

to:

```<code>Question question = new Question("Favorite color?");
Choice c1 = new Choice(question, "red"); // or just: questionId instead of question?
Choice c2 = new Choice(question, "blue");// the same

questionRepository.store(question);
choiceRepository.store(c1, c2);
</code>```

Now we do not need to 'assign' anything to the Question and we don't need to maintain the collection. For example, this collection may vary - it may be collection of just approved choices, or voted choices, or top 3 voted choices etc. We are not able to expressed what kind of relationship is that just by having getChoices().

So should we even go further to have a rule like:

Don't compose Aggregates with other Entities. Just have a root Entity and value objects. Use reverse relationship to express the connection between aggregate roots.

Make sense?

答:
Choice has Reference to Question

Makes sense if this is a composite, vice an aggregate.

Inadequate Requirements Analysis

Don't compose Aggregates with other Entities. Just have a root Entity and value objects. Use reverse relationship to express the connection between aggregate roots.

Make sense?

No, it does not.

It's not possible to make such global, absolute, diktats. Your requirements, use cases, will inform the class hierarchies and relationships.

it may be collection of just approved choices, or voted choices, or top 3 voted choices etc. We are not able to expressed what kind of relationship is that just by having getChoices()

Sounds like the Choice class needs Approved and Votes properties. Now, getting the "top 3 voted choices" would be quite easy.

Consider: class Choice : IComparable<Choice> then you can Sort() a List<Choice> based on Votes

I agree that all of this could also be achieved via a reverse relation, but would be more complicated in my opinion. For example, if I would have a reverse relation and want to delete a question, I would have to iterate through all choices to pick the ones that are related to this specific question.

So what if a collection must be iterated. That's what they're for. The .net framework goes to a lot of trouble to help you do this in a whole lot of ways.

Besides, you do not have to "iterate throught all choices", because Question has a choices property. So, select a choice to delete, get its Question reference, get that question's choices reference. Now you have all the choices.

Class design is not database design

Choice c1 = new Choice(question, "red"); // or just: questionId instead of question?

This, et.al. sounds like you want your class design to reflect the database design. Consider this stackoverflow question

ContentLicense: CC BY-SA 3.0


问:
Does code format affect performance?
I think I have came across a few times when I reformat some segment of code, it performed the way I wanted it to other than the other poorly formatted segment of code? Does code format affect performance? Or is that a myth?</p>

答:
To the compiler/interpreter it matters very little how well formatted and/or commented your code is. It only increases the parsing time by a very tiny amount because the parser has more characters to process (and mostly skip).

In most languages, the compiler/interpreter would be perfectly happy if you present your code as a single long line without any comments at all.

On the other hand, for human readers (including you in a few months time) it makes a world of difference if the code is well-formatted, well-commented and easily readable.

With well-written code, you can usually glance over it to get an idea of what the code is doing. If the code has poor or no formatting,then you really have to pay attention to understand the code which takes significantly more time and energy.

Title: Does code format affect performance?


问:
How common is prototyping as the first stage of development?
I've been taking some software design courses in the past few semesters, and while I see the benefit in a lot of the formalism, I feel like it doesn't tell me anything about the program itself:

You can't tell how the program is going to operate from the Use Case spec, even though it discusses what the program can do.

You can't tell anything about the user experience from the requirements document, even though it can include quality requirements.

Sequence diagrams are a good description of how the software works as the call stack, but are very limited, and give a highly partial view of the overall system.

Class diagrams are great for describing how the system is built, but are utterly useless in helping you figure out what the software needs to be.

Where in all this formalism is the bottom line: how the program looks, operates, and what experience it gives? Doesn't it make more sense to design off of that? Isn't it better to figure out how the program should work via a prototype and strive to implement it for real?

I know that I'm probably suffering from being taught engineering by theoreticians, but I need to ask, do they do this in the industry? How do people figure out what the program actually is, not what it should conform to? Do people prototype a lot, or do they mostly use the formal tools like UML and I just didn't get the hang of using them yet?

答: My personal observation is that prototyping is given much lip service but all too often the prototype, once it is showing signs of life, is simply rebranded as 'Beta' or, even worse, v1.0.</p>

ContentLicense: CC BY-SA 2.5


答:
I believe that the gang of four themselves classify design patterns as

a common solution to a commonly occurring problem*

So yes, the patterns are relevant when the same type of problem occurs. And this brings us to a problem with the term "Design Pattern". A pattern is something recognizable that occurs repeatedly. So in reality there is not a pattern of designs, there is a pattern of problems.

Some programming languages may have native solutions to some of those problems. The "Design Patterns" book itself mentions that the visitor pattern is of little value if you are using CLOS, as multi-dispatch is natively supported by CLOS, the very problem that the Visitor pattern is trying to solve.

Also, the .NET framework has a build in event mechanism for publishing events to multiple listeners, making the Observer pattern less relevant in this context.

The change from desktop applications to web applications** also change the type of programming problems we have to solve. Many of the patterns in the book "Design Patterns" are relevant for desktop applications, but not so much for web applications. Of course, with single page apps, these patterns may be relevant again on the client-side.

But the design patterns, and books like "Design Patterns", or "Patterns of Enterprise Application Architecture" are of huge value when you are a novice programmer and faced with a new type of problem for the first time; as I was the first time I was asked to implement Undo functionality. Had it not been for the "Design Patterns" book, my implementation would probably had been something like storing a snapshot of the data after each state-changing operation*** - a very error prone, and horribly inefficient, approach.

So yes, some of the pattern become less relevant over time, and as you become an experienced programmer, you think less about them. But to a novice, they are valuable, as long as you remember that they are the means to solve a problem - and not a quest to use as many as possible.

* quote may not be 100% accurate as it is taken from memory

** in my experience, it is getting very common for enterprises to choose web delivery mechanisms for internal line-of-business applications.

*** after learning functional programming and functional data structures, then that might actually be the way I would solve it today.

Title: Are design patterns really essential nowadays?

Body:
I was reading "Coders at Work" and have faced the fact that some of the professionals interviewed in the book are not so enthusiastic about design patterns.

I think that there are 2 main reasons for this:

Design patterns force us to think in their terms. In other words, it's almost impossible to invent something new (maybe better).

Design patterns don't last forever. Languages and technologies change fast; therefore, design patterns will eventually become irrelevant.

So maybe it's more important to learn how to program properly without any particular patterns and not to learn them.

The point also was that usually when people face a problem and they don't have much time, they try to use a pattern. This means copying and pasting existing code into your project with minor changes in order to get it working. When it's time to change or add something, a developer doesn't know where to start because it's not his code and he's not deeply familiar with it.


问:
Building a string parser for user command and control?
My goal is to build a command parser that has basic syntax and multiple possible branches at each point. These commands come from users of the system and are text input (no GUI). The basic syntax is base_command [sub_command [optional_parameters]], where optional_parameters is a space seperated list of parameters.

Examples:

```<code>add event "Program-a-thon"
add notification program-a-thon meeting
add pattern "follow the white rabbit"
remove event "Program-a-thon"
remove notification meeting
remove pattern "follow the white rabbit"
edit pattern "follow the white rabbit" "follow the white tiger"
reload settings
</code>```

As you can see, I have 4 base commands (add, remove, edit and reload). However, I anticipate adding more in the future. I also have 4 subcommands (event, notification, pattern and settings). However, edit only has 1 subcommand and settings only applies to the reload base command. Not all subcommands are associated with all base commands. Finally, I have parameters. For simplicity, I am planning on making these position based.

I am writing this application in Python (utilizing the 2.7 branch).

So far, I've come up with this:

Utilize the .split() command and take the first two results to get the command and base command. The third index (if it exists) will be the positional arguments.

OR

Utilize a regular expression to get the base command and sub-command. The third index will be positional arguments.

Then utilizing this information, look at a dictionary like this to see if the command/sub-command option is viable. If it is, call the method described in the commands[base_command][sub_command]['method'] key to perform my action.

The upside of this is that I can easily tell if the command/subcommand combination is valid. The downside is maintaining such a dictionary and possibly extending it if I wish to add more options or information. For just these few commands I already have a dictionary like this (with some supporting attributes)

```<code>commands =
{
    'add' :
    {
        'help_text' : "Add a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Add an event",
                    'method' : "add_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Recieve a notification for events that are tagged with the values you wish (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "add_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "add_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'remove':
    {
        'help_text': "Remove a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Remove an event",
                    'method' : "remove_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Remove a notification for specific tags (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "remove_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "remove_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'edit':
    {
        'help_text': "Edit an existing `pattern`",
        'sub_commands': {
                'pattern' : {
                    'help_text' : "Edit a pattern pattern to watch for in new event descriptions (old_pattern, new_pattern)",
                    'method' : "edit_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'reload':
    {
        'help_text': "Reload application options",
        'sub_commands': {
                'settings' : {
                    'help_text' : "Reload the settings of the application",
                    'method' : "reload_settings",
                    'permissions' : 'owner',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
}
</code>```

My questions are, how do I properly design the parser so that I can

Extend the command tree easily in the future?

Have a combination of sub-commands that may or may not apply to all base commands?

And

Is utilizing a dictionary, like above, worth the hassle of maintenance when adding commands? I realize that commands will be 'relatively' stable (once added, modifications will be rare to the dictionary itself). However, when I do add them, they will probably come in at least pairs (add and remove), meaning the potential for messing up the dictionary occurs in multiple places.

答:
Have a look at the Python argparse and cmd modules. If you'd like to make an interactive UI, subclass cmd.Cmd and for each of the commands, you can use argparse to parse the subcommand and options.

```<code>import readline # for history and autocomplete
import cmd

class MyShell(cmd.Cmd):
    def do_add(self, line):
        "adds various things"
        print "add called with arguments", line # here you can use argparse on line

>>> MyShell().cmdloop()
(Cmd) xyz
*** Unknown syntax: xyz
(Cmd) help

Documented commands (type help <topic>):
========================================
add  help

(Cmd) help add
adds various things
(Cmd) add
add called with arguments
(Cmd) add 1 2 3 4
add called with arguments 1 2 3 4
(Cmd)
</code>```

Body:
Have a look at the Python argparse and cmd modules. If you'd like to make an interactive UI, subclass cmd.Cmd and for each of the commands, you can use argparse to parse the subcommand and options.

import readline # for history and autocomplete
import cmd

class MyShell(cmd.Cmd):
    def do_add(self, line):
        "adds various things"
        print "add called with arguments", line # here you can use argparse on line

>>> MyShell().cmdloop()
(Cmd) xyz
*** Unknown syntax: xyz
(Cmd) help

Documented commands (type help <topic>):
========================================
add  help

(Cmd) help add
adds various things
(Cmd) add
add called with arguments
(Cmd) add 1 2 3 4
add called with arguments 1 2 3 4
(Cmd)


问:
Interface to enumerate over files
I'm trying to design a generic interface for enumerating over a list files. Each iteration will open a file, allow the consuming code to access the file to perform some task, and then close the file.

At first this seemed like like a simple enumeration pattern, but the consuming code actually needs to know the status of each file both after it is opened and after it is closed. So rather then having a single MoveNext() method my interface has OpenNextFile() and CloseCurrentFile() methods, each of which may return a failure status. In addition, CloseCurrentFile() needs a way to report whether each file was saved or not when it was closed.

Here's my current interface.

```<code>public interface IFileEnumerator
{
    //The following properties reflect the current state of the IFileEnumerator
    FileEnumeratorStatus Status { get; }
    string StatusMessage { get; }
    string FileName { get; }
    byte[] FileData { get; }

    //Attempts to open the next file
    FileEnumeratorStatus OpenNextFile();

    //Closes the current file
    FileEnumeratorStatus CloseCurrentFile();
}

public enum FileEnumeratorStatus
{
    AtStart, //Files have not been opened
    Opened, //File currently opened
    Opened_Failed, //Failed to open file
    Close_Saved, //File closed and saved
    Closed_NotSaved, //File closed and not saved
    Close_SaveFailed, //File closed saving failed
    AtEnd //No more files
}
</code>```

Here's an example of the consuming code:

```<code>//FileProcessor is a class which run a ProcesssJob on a set of files returned by a
//IFileEnumerator and returns a ProcesssingJobResult with results of all the files
public class FileProcessor
{
    public ProcesssingJobResult RunJob(IFileEnumerator fileEnumerator, ProcesssJob job)
    {
        List<FileProcessingResult> resultList = new List<FileProcessingResult>();

        while (fileEnumerator.OpenNextFile() != FileEnumeratorStatus.AtEnd)
        {
            FileProcessingResult currentFileResult = new FileProcessingResult();
            currentFileResult.FileName = fileEnumerator.FileName;

            if (fileEnumerator.Status == FileEnumeratorStatus.Opened)
            {
                currentFileResult.JobCompleted = job.RunJob(fileEnumerator.FileData);

                var closureStatus = fileEnumerator.CloseCurrentFile();

                if (closureStatus == FileEnumeratorStatus.Close_Saved)
                    currentFileResult.Saved = true;
                else if (closureStatus == FileEnumeratorStatus.Closed_NotSaved)
                    currentFileResult.Saved = false;
                else if (closureStatus == FileEnumeratorStatus.Close_SaveFailed)
                {
                    currentFileResult.Saved = false;
                    currentFileResult.Message = fileEnumerator.StatusMessage;
                }
            }
            else if (fileEnumerator.Status == FileEnumeratorStatus.Opened_Failed)
            {
                currentFileResult.JobCompleted = false;
                currentFileResult.Message = fileEnumerator.StatusMessage;
                currentFileResult.Saved = false;
            }

            resultList.Add(currentFileResult);
        }

        ProcesssingJobResult jobresult = new ProcesssingJobResult();
        jobresult.TimeStamp = DateTime.Now.ToUniversalTime();
        jobresult.Machine = System.Environment.MachineName;
        jobresult.User = System.Environment.UserName;
        jobresult.Results = resultList;

        return jobresult;
    }
}

//A generic task that can be run on a file
public interface ProcesssJob
{
    bool RunJob(byte[] data);
}

//Result of processing one file
public class FileProcessingResult
{
    public bool JobCompleted { get; set; }
    public bool Saved { get; set; }
    public string FileName { get; set; }
    public string Message { get; set; }

}

//The overall result of processing a set of files
public class ProcesssingJobResult
{
    public DateTime TimeStamp { get; set; }
    public String Machine { get; set; }
    public String User { get; set; }
    public List<FileProcessingResult> Results { get; set; }
}
</code>```

Maybe this is just a question of careful documentation, but I'm having trouble dealing with all these different possible states. Drawing a state diagram doesn't help as it's possible to go from every state to just about every other state. Should the consuming code call CloseCurrentFile() if OpenNextFile() return Open_Failed? What if it does? Would a Closed status be returned even if a file was never opened? If CloseCurrentFile() was not called after OpenNextFile() should it be closed automatically by the next call to OpenNextFile() or should an exception be thrown? I'd rather someone implementing this interface not have to worry about getting all this right.

The problem is much simpler if I have a single OpenNextFile() method which is responsible for both closing the last opened file, and opening the next file. Yet then this single method needs to report both the result of opening the next file, as well as closing the last file. This also becomes tricky for consuming code as the final state of each file is not determined until the following iteration.

```<code>public interface IFileEnumerator_Alternate
{
    string FileName { get; }
    byte[] FileData { get; }
    string StatusMessage {get;}

    //Closes the previous file, and opens the next file
    Result OpenNextFile();
}

public class Result
{
    public bool CurrentFileOpened {get; set;}
    public string CurrentFileName {get; set;}
    public string CurrentFileStatusMessage {get; set;}

    public string LastFileName {get; set;}
    public bool LastFileClosedOk {get; set;}
    public string LastFileClosedStatusMessage {get; set;}
    public bool LastFileSaved {get; set;}
}
</code>```

Is there another way to look at this, or some other common design pattern that is more suited to what I'm trying to do? Here's an activity diagram showing the overall process.

答:
I think that you should separate enumerating over files and handing each particular file.

There already is an interface in .Net for enumerating: IEnumerable<T>, so I would use that.

That leaves working with a single file: that would look pretty much like your IFileEnumerator, except with the enumerator parts removed.

I also don't think that opening and closing should use the same status enum.

```<code>public interface IFile
{
    string FileName { get; }
    byte[] FileData { get; }

    bool Open();

    FileCloseStatus Close();
}

public enum FileCloseStatus
{
    Saved, //File closed and saved
    NotSaved, //File closed and not saved
    SaveFailed, //File closed saving failed
}
</code>```

Title: Interface to enumerate over files

Body:
I think that you should separate enumerating over files and handing each particular file.

There already is an interface in .Net for enumerating: IEnumerable<T>, so I would use that.

That leaves working with a single file: that would look pretty much like your IFileEnumerator, except with the enumerator parts removed.

I also don't think that opening and closing should use the same status enum.

public interface IFile
{
    string FileName { get; }
    byte[] FileData { get; }

    bool Open();

    FileCloseStatus Close();
}

public enum FileCloseStatus
{
    Saved, //File closed and saved
    NotSaved, //File closed and not saved
    SaveFailed, //File closed saving failed
}


问:
Accessing struct attribute: casting vs field name
I was just going over some kernel code, I noticed that rb->__rb_parent_color = (unsigned long)p | color; is kinda wired. The first field of a struct is accessed by casting the pointer and not by using the field name.

Here is the definition of that struct, as you can see the color is the first attribute, so simply casting (unsigned long)p will give us the same as rb->__rb_parent_color. But why did the developers choose to do it this way and not using the ->?

The only reason I can think of is compiler optimizations that are not done when using rb->__rb_parent_color, but find this hard to believe cause it seems like the compiler will, in both cases, calculate the same offset without problems.

答:
struct rb_node *p is not dereferenced. Read it again: this code casts the address to an unsigned long.

This is relying on the fact that object addresses are aligned such that the bottom bit (at least) of the address is guaranteed to be un-used, so it packs the colour into that bit. So __rb_parent_color here does not mean the parent's color: it means the parent pointer and its color are stored in this field.

Read the __rb_parent and __rb_color macros above to see how the field is used. (__rb_parent actually implies the bottom 2 bits are un-used, giving 4-byte alignment, but nothing seems to use the second bit either way.)


问:
Generics in low level languages
I'm developing a language like Vala and OOC that compiles back to C.

This means that, eventually, every feature needs to be adoptable to C code in some way or another. Generics is one of the features I'd like to implement in my language.

As you probably know, C is a strictly typed language. Except for the opaque void pointer, there is no way to pass an argument of a unknown type. This is because the compiler needs to know the exact size of the argument passed or returned.

The following solutions come to my mind:

Boxing: Create a union that can store every possible type

Pass a pointer to the parameter, rather than the parameter itself.

Both of these have their downsides:

The size of the generic type T will be equal to the largest possible type

The sizes are predetermined, a struct with a different size cannot be passed by value

Slower, because every argument has to be boxed/unboxed

The parameter is not copied onto the new stack scope

Memory management issues because of the above

Not the desired behaviour because of the above

I'm interested in knowing how I could adopt this high-level principle in a lower level language, and also how other high-level languages have conquered this problem.

EDIT

As @delnan has pointed out, another possibility is Monomorphization, creating a new function for every data type. This has a few of the same downsides:

The type T needs to be defined beforehand (not very generic)

The binary size gets larger (which, granted, isn't very relevant nowadays)

答:
Monomorphization. For every generic (polymorphic) type/function, generate a non-generic (monomorphic) version for every set of type parameters. Given these declarations:

```<code>struct G<T> {
  a: T,
  b: T
}

fn get_a<T>(g: G<T>) -> T {
  return g.a;
}
</code>```

and this code:

```<code>x = G<int>(1, 2);
y = G<float>(1.0, 2.0);
get_a(x);
get_a(y);
</code>```

Generate code equivalent to:

```<code>struct G_int {
  a: int,
  b: int
}

struct G_float {
  a: float,
  b: float
}

fn get_a_int(g: G_int) -> int {
  return g.a;
}

fn get_a_float(g: G_float) -> float {
  return g.a;
}

x = G_int(1, 2);
y = G_float(1.0, 2.0);
get_a_int(x);
get_a_float(y);
</code>```

This also works across library barriers! It requires the code (at least in AST/IR form) of generics to be included with library binaries, but aside from that the compiler can simply generate the code in the same way, just taking the "template" from a different source. Duplicate definitions (when two libraries instantiate the same generic with the same type parameters) can be merged by the linker and at worst increase compile time.

Title: Generics in low level languages

Body:
Monomorphization. For every generic (polymorphic) type/function, generate a non-generic (monomorphic) version for every set of type parameters. Given these declarations:

struct G<T> {
  a: T,
  b: T
}

fn get_a<T>(g: G<T>) -> T {
  return g.a;
}

and this code:

x = G<int>(1, 2);
y = G<float>(1.0, 2.0);
get_a(x);
get_a(y);

Generate code equivalent to:

struct G_int {
  a: int,
  b: int
}

struct G_float {
  a: float,
  b: float
}

fn get_a_int(g: G_int) -> int {
  return g.a;
}

fn get_a_float(g: G_float) -> float {
  return g.a;
}

x = G_int(1, 2);
y = G_float(1.0, 2.0);
get_a_int(x);
get_a_float(y);

This also works across library barriers! It requires the code (at least in AST/IR form) of generics to be included with library binaries, but aside from that the compiler can simply generate the code in the same way, just taking the "template" from a different source. Duplicate definitions (when two libraries instantiate the same generic with the same type parameters) can be merged by the linker and at worst increase compile time.


答:
currently there are 2 ways;

the type erasure method of java; essentially everything becomes a void* (or a custom type like a struct base{void** functptrs;} and gets casted to and fro as needed, this requires the type to follow a certain interface to let the template figure out if casts are valid at runtime.

instantiation creates a new definition of the template like delnan explained; this is what is used in C++. It does cause some code bloat as you need to let the client recompile the template each time it is used.

Title: Generics in low level languages

Body:
I'm developing a language like Vala and OOC that compiles back to C.

This means that, eventually, every feature needs to be adoptable to C code in some way or another. Generics is one of the features I'd like to implement in my language.

As you probably know, C is a strictly typed language. Except for the opaque void pointer, there is no way to pass an argument of a unknown type. This is because the compiler needs to know the exact size of the argument passed or returned.

The following solutions come to my mind:

Boxing: Create a union that can store every possible type

Pass a pointer to the parameter, rather than the parameter itself.

Both of these have their downsides:

The size of the generic type T will be equal to the largest possible type

The sizes are predetermined, a struct with a different size cannot be passed by value

Slower, because every argument has to be boxed/unboxed

The parameter is not copied onto the new stack scope

Memory management issues because of the above

Not the desired behaviour because of the above

I'm interested in knowing how I could adopt this high-level principle in a lower level language, and also how other high-level languages have conquered this problem.

EDIT

As @delnan has pointed out, another possibility is Monomorphization, creating a new function for every data type. This has a few of the same downsides:

The type T needs to be defined beforehand (not very generic)

The binary size gets larger (which, granted, isn't very relevant nowadays)


问:
Reduce Operations on Distributed Databases
I would like to ask you about optimizing reduce operations (e.g. count) on multiple databases.

Let's say there is a user table that is stored in various countries and sharding is made based on the country field of the entity row. Think this as a situation where sharding and replication can occur so same record may exist in another database. At this point does "coming up with a solution where all the unique keys of entities of this table stored in a central database with maybe where the real record is" sound stupid and implies that I know nothing about the subject or a good way to solve the issue and there are a lot of examples in enterprise applications?

Thank you for your answers.

答:
The short answer is that if you've set things up properly, it's a waste of both space and time to keep a separate central master mapping of which primary keys exist globally.

Your sharding function tells you which shard has is authoritative for a given primary key.  A central master list of which rows are currently in the distributed database would be an aggregation across shards of the list of primary keys for which that shard is authoritative.  Keeping this central mapping consistent with the sets of keys present on each shard introduces unnecessary overhead, and quickly becomes a bottleneck for all database modifications on any shard globally.  All row insertions or deletions would require querying this central master mapping to see if it's consistent, possibly followed by modifying the central master mapping.

Even with your proposed master mapping of primary keys to shards, you still need to contact each shard in order to perform your reduction.  (Of course, you skip any shards that your sharding function tells you don't contain any rows relevant to your reduction operation.)

If your proposed master list can answer your query without contacting the shards, you probably wouldn't want to query it anyway, since it's already a bottleneck for all write operations.  You could of course shard this master list of primary keys for better performance, but then it ceases to be the proposed central list of primary keys.  This would be better thought of as a second read-only distributed database that contains a mirror of a subset of the columns in your primary distributed database.  Now, a second distributed read-only copy of a subset of your data does make sense for some usage patterns.  However, how much sense it makes is highly dependent on your usage patterns and does introduce some replication delay between the primary distributed database and the secondary distributed database.


问:
Should a getter throw an exception if its object has invalid state?
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem.

Suppose that I have a class that has a String name field and a String surname field.

Then it uses those fields to compose the complete name of a person in order to display it on some sort of document, say an invoice.

```<code>public void String name;
public void String surname;

public String getCompleteName() {return name + " " + surname;}

public void displayCompleteNameOnInvoice() {
    String completeName = getCompleteName();
    //do something with it....
}
</code>```

Now I want to strengthen the behavior of my class by throwing an error if the displayCompleteNameOnInvoice is called before the name has been assigned. It seems a good idea, doesn't it?

I can add a exception-raising code to getCompleteName method.
But in this way I'm violating an 'implicit' contract with the class user; in general getters aren't supposed to throw exceptions if their values aren't set. Ok, this is not a standard getter since it does not return a single field, but from the user point of view the distinction may be too subtle to think about it.

Or I can throw the exception from inside the displayCompleteNameOnInvoice. But to do so I should test directly name or surname fields and doing so I would violate the abstraction represented by getCompleteName. It's this method responsibility to check and create the complete name. It could even decide, basing the decision on other data, that in some cases it is sufficient the surname.

So the only possibility seems to change the semantic of the method getCompleteName to composeCompleteName, that suggests a more 'active' behavior and, with it, the ability of throwing an exception.

Is this the better design solution? I'm always looking for the best balance between simplicity and correctness. Is there a design reference for this issue?

答: Do not permit your class to be constructed without assigning a name.</p>


答:
I'm not a Java guy, but this seems to adhere to both constraints you presented.

getCompleteName does not throw an exception if the names are uninitialized, and displayCompleteNameOnInvoice does.

```<code>public String getCompleteName()
{
    if (name == null || surname == null)
    {
        return null;
    }
    return name + " " + surname;
}

public void displayCompleteNameOnInvoice()
{
    String completeName = getCompleteName();
    if (completeName == null)
    {
        //throw an exception.
    }
    //do something with it....
}
</code>```

Title: Should a getter throw an exception if its object has invalid state?

Body:
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem.

Suppose that I have a class that has a String name field and a String surname field.

Then it uses those fields to compose the complete name of a person in order to display it on some sort of document, say an invoice.

```<code>public void String name;
public void String surname;

public String getCompleteName() {return name + " " + surname;}

public void displayCompleteNameOnInvoice() {
    String completeName = getCompleteName();
    //do something with it....
}
</code>```

Now I want to strengthen the behavior of my class by throwing an error if the displayCompleteNameOnInvoice is called before the name has been assigned. It seems a good idea, doesn't it?

I can add a exception-raising code to getCompleteName method.
But in this way I'm violating an 'implicit' contract with the class user; in general getters aren't supposed to throw exceptions if their values aren't set. Ok, this is not a standard getter since it does not return a single field, but from the user point of view the distinction may be too subtle to think about it.

Or I can throw the exception from inside the displayCompleteNameOnInvoice. But to do so I should test directly name or surname fields and doing so I would violate the abstraction represented by getCompleteName. It's this method responsibility to check and create the complete name. It could even decide, basing the decision on other data, that in some cases it is sufficient the surname.

So the only possibility seems to change the semantic of the method getCompleteName to composeCompleteName, that suggests a more 'active' behavior and, with it, the ability of throwing an exception.

Is this the better design solution? I'm always looking for the best balance between simplicity and correctness. Is there a design reference for this issue?

Body:
I'm not a Java guy, but this seems to adhere to both constraints you presented.

getCompleteName does not throw an exception if the names are uninitialized, and displayCompleteNameOnInvoice does.

public String getCompleteName()
{
    if (name == null || surname == null)
    {
        return null;
    }
    return name + " " + surname;
}

public void displayCompleteNameOnInvoice()
{
    String completeName = getCompleteName();
    if (completeName == null)
    {
        //throw an exception.
    }
    //do something with it....
}


答:
The answer provided by DeadMG pretty much nails it, but let me phrase it a bit differently: Avoid having objects with invalid state. An object should be "whole" in the context of the task it fulfills. Or it should not exist.

So if you want fluidity, use something like the Builder Pattern. Or anything else that is a separate reification of an object in construction as opposed to the "real thing", where the latter one is guaranteed to have valid state and is the one that actually exposes the operations defined on that state (e.g. getCompleteName).


问:
How do you apply Single Responsibility principle to a repository
I am trying to apply "SOLID" whenever I can and try to use common sense and avoid a pattern when I see that a pattern is creating more problems than it's trying to solve. I don't want to apply a pattern and make life difficult for somebody else using my code just for the sake "I write patterns" if you see what I mean.

Now I am struggling with one of the principles that I thought was the easiest to grasp: "SRP".

How do you practically apply this principle to repositories?

Let's suppose I have a

```<code>IEmployeeRepository
IUserRepository
IProductRepository
</code>```

and commonly they will have methods like these:

```<code>public interface IUserRepository
{
    User GetUser(int id);
    IEnumerable<User> GetAllUser();
    void DeleteUser(int id);
}
</code>```

same for employees and products.

Are we saying that each of these method should be a class on it's own? even though at times we are talking a single line of code?

答:
Whenever you have a class with more than 1 method, you can question if the SRP is fulfilled, since each of the methods will (typically) solve a different task or problem and so has a "different responsibility". But that's actually not the way I understand the SRP - SRP means IMHO "single responsibility at the correct level of abstraction". And the level of abstraction for a repository may be

"repository RX is responsible for providing abstract CRUD operations for class X"

In fact, when you start implementing such a repository, it may turn out that some of the member functions of the repo may become so complex that you need additional helper classes to implement them. If that's the case, the repo may turn into a facade, but the responsibilty stays the same - at that level of abstraction.

In fact, there is no "absolute rule" how to choose the "correct" levels of abstraction. There are guidelines like

the "one reason to change" mantra, or

simple indicators like the code size, number of parameters of certain methods or

the problem of coming up with a concise name, or

the possibility of distributing the maintenance, evolvement and requirements management of pieces of software to different people or organizational units (citing Bob Martin: "This principle is about people")

But at the end of the day,  this is up to your experience and to some degree of your taste.

ContentLicense: CC BY-SA 4.0


答:
I think you should think who has an interest to change that respective class. For example if you have an User class with an CalculatePay method and a save method. The accountant would want to change the CalculatePay and the DB administrator the save method. These are two different responsibilities.

The SRP means grouping together things that change for the same reason. So the repository shouldn't violate the SRP.

Title: How do you apply Single Responsibility principle to a repository

Body:
I am trying to apply "SOLID" whenever I can and try to use common sense and avoid a pattern when I see that a pattern is creating more problems than it's trying to solve. I don't want to apply a pattern and make life difficult for somebody else using my code just for the sake "I write patterns" if you see what I mean.

Now I am struggling with one of the principles that I thought was the easiest to grasp: "SRP".

How do you practically apply this principle to repositories?

Let's suppose I have a

```<code>IEmployeeRepository
IUserRepository
IProductRepository
</code>```

and commonly they will have methods like these:

```<code>public interface IUserRepository
{
    User GetUser(int id);
    IEnumerable<User> GetAllUser();
    void DeleteUser(int id);
}
</code>```

same for employees and products.

Are we saying that each of these method should be a class on it's own? even though at times we are talking a single line of code?


问:
Does code formatting have to matter?
UPDATE: an issue would arise from stuff that is not strictly defined by a formatter, like consecutive empty lines etc., that would get lost in the process (local to server to local reformatting) which would annoy people (me as well :)

I'm used to adopting some shared code formatter so my question is not about "should I submit to that?"

I wonder does this (code formatting) have to matter at all? Isn't it possible to have your repository store your commmits in some "default" formatting? You would never get to see what that style looks like, because every time you checkout all the sources get saved to your HDD after getting reformatted using YOUR formatter. Also every time you would browse the repository your client would show you the source reformatted using YOUR formatter. Also all diffs would be done after reformatting using YOUR formatter.

Is this possible to do? (E.g. client plugins, repository configuration, etc.)

答:
Technically, the main problem I see is with line numbers and debugging.
If you reformat the code, code might end-up on different lines, making it much harder to make sense of stacktraces and such. Also referring to code in general would be much harder, if your colleagues see different lines than you.

In context of collaboration, I think recognizability of the code is important. If I look at the same code on the screen of a colleague, it would be much harder to collaborate if I don't easily recognize the code.

Title: Does code formatting have to matter?


问:
Am I using Data Warehousing wrong?
I work for a company that has several products, and several databases and tons of data.

To sorta merge all this data what we've been doing moving some of our data over to Amazon Redshift (a data warehouse).  We store as much as we can here (everything very de-normalized).  We consider redshift our 'source' data, as we've changed a lot of procedures to pretty much just bulk insert straight to the data warehouse before going to any other database first.

The part I'm having a hard time understanding is I thought a data warehouse was suppose to help with reporting.

With Amazon Redshift, they have disabled stored procedures, recursive ctes, user defined functions and a bunch of other things..which makes it sorta tough to report on data.

What we do in a lot of situations, is export the data from redshift into a different database, just so we can run some reports  (not all the data, we just export the data that is relevant to the report).

Some other reports that are run we have set up programs that dynamically produce the sql and send in the ad-hoc query to get the data we need, these programs become a pretty good mess after too much modification (concatenating strings to make the sql, hard to test without just running the program ect)

This all seems sorta wrong, are we using the concept of data warehousing wrong?

答:
If I understand your methods, you are treating Redshift as a data junk-pile and must pre-process the junk before you can run typical reports upon it. The pre-processing step is the exporting data that is relevant to a particular report.

If you were using Redshift as it was intended, it should act just like a database (because it is). However, this will likely take considerable effort to restructure the junk-pile. Contrariwise, the effort ought be rewarded many-fold as you'll not have to spend time doing custom extractions.

Redshift has substantial tutorials on how to use the product; I'd start there.

Title: Am I using Data Warehousing wrong?


答:
Don't have an object with an invalid state.

The purpose of a constructor or builder is to set the state of the object to something that is consistent and usable.  Without this guarantee, problems crop up with improperly initialized state in objects.  This issue becomes compounded if you're dealing with concurrency and something can access the object before you are completely done setting it up.

So, the question for this part is "why are you allowing the name or surname to be null?"  If that isn't something that is valid in the class for it to work properly, don't allow it.  Have a constructor or builder that properly validates the creation of the object and if it isn't right, raise the issue at that point.  You may also wish use one of the @NotNull annotations that exists to help communicate that "this cannot be null" and enforce it in coding and analysis.

With this guarantee in place, it becomes much easier to reason about the code, what it does, and not have to throw exceptions in odd places or put excessive checks around getter functions.

Getters that do more.

There is quite a bit out there on this subject.  You've got How Much Logic in Getters and What should be allowed inside getters and setters? from here and getters and setters performing additional logic over on Stack Overflow.  This is an issue that comes up again and again in class design.

The core of this comes from:

in general getters aren't supposed to throw exceptions if their values aren't set

And you are right.  They shouldn't.  They should look 'dumb' to the rest of the world and do what is expected.  Putting too much logic in there leads to issues where the law of least astonishment is violated.  And lets face it, you really don't want to be wrapping the getters with a try catch because we know how much we love doing that in general.

There are also situations where you must use a getFoo method such as the JavaBeans framework and when you have something from EL calling expecting to get a bean (so that <% bar.foo %> actually calls getFoo() in the class - setting aside the 'should the bean be doing the composition or should that be left to the view?' because one can easily come up with situations where one or the other can clearly be the right answer)

Realize also that it is possible for a given getter to be specified in an interface or to have been part of the previously exposed public API for the class that is getting refactored (a previous version just had 'completeName' that was returned and a refactoring broke it into two fields).

At the end of the day...

Do the thing that is easiest to reason about.  You will spend more time maintaining this code than you will spend designing it (though the less time you spend designing, the more time you will spend maintaining).  The ideal choice is to design it in such a way that it won't take as much time to maintain, but don't sit there thinking about it for days either - unless this really is a design choice that will have days of implications later.

Trying to stick with semantic purity of the getter being private T foo; T getFoo() { return foo; } will get you into trouble at some point.  Sometimes the code just doesn't fit that model and the contortions that one goes through to try to keep it that way just doesn't make sense... and ultimately makes it harder to design.

Accept sometimes that the ideals of the design can't be realized the way you want them in the code.  Guidelines are guidelines - not shackles.


答:
Instead of thinking of data warehouse as a warehouse (store as much as we can, very denormalised), to get the benefit you need to think about what benefit you want to get out of it. Basically, in data warehouse, instead of having just data, you have Facts and Measures (Dimensions). After you build these Facts and Dimensions, you will get what's called a snow flake schema, i.e. not very normalised.

If you have reports that rely on stored procedures, user defined functions, etc. you probably need to update them to take advantage of the data warehouse schema. Done correctly, reports should only need some joins and maybe special calculations which are stored in some libraries, not in database.

Another way to use data warehouse is using OLAP libraries, it's like SQL for data warehouse. OLAP queries work on data warehouse Cube, which is collection of Facts and Dimension. OLAP libraries will translate them to SQL queries.

Also, it's probably easier to understand how to build data warehouse using ETL tools before start storing data straight to data warehouse so you can understand what transformations would be needed. In the end, it should be easy to get reports and analytics out of your data warehouse using off the shelf applications.

Title: Am I using Data Warehousing wrong?

Body:
I work for a company that has several products, and several databases and tons of data.

To sorta merge all this data what we've been doing moving some of our data over to Amazon Redshift (a data warehouse).  We store as much as we can here (everything very de-normalized).  We consider redshift our 'source' data, as we've changed a lot of procedures to pretty much just bulk insert straight to the data warehouse before going to any other database first.

The part I'm having a hard time understanding is I thought a data warehouse was suppose to help with reporting.

With Amazon Redshift, they have disabled stored procedures, recursive ctes, user defined functions and a bunch of other things..which makes it sorta tough to report on data.

What we do in a lot of situations, is export the data from redshift into a different database, just so we can run some reports  (not all the data, we just export the data that is relevant to the report).

Some other reports that are run we have set up programs that dynamically produce the sql and send in the ad-hoc query to get the data we need, these programs become a pretty good mess after too much modification (concatenating strings to make the sql, hard to test without just running the program ect)

This all seems sorta wrong, are we using the concept of data warehousing wrong?


问:
Is it possible to programmatically attach custom metadata to phone calls?
I'm trying to determine if it should be possible for a cell phone app to relay custom data along with a phone call. By "should be possible" I mean that I'm not trying to learn how to do it in iOS/Android/whatever, I'm just trying to determine if:

It is permitted by standards: the standards for the metadata that initiates a phone call allow for it to be extended. (I found all kinds of information about high level phone call APIs and CDRs which are kept after a phone call is made, but nothing in the "this is the data header that leaves your phone when you make a call" category).

I can be sure that my custom data will be forwarded intact by the cellular network nodes.

This type of functionality is typically available to apps (from my research: some cellular functionality is implemented by firmware, other functionality has legal issues and its APIs are restricted to privileged users).

In short, what I would ideally like to hear is something along the lines of:
"When you initiate a phone call, the phone generates this header. This part of the header can be used to send custom data, and cellular network nodes won't mess with it. The API for this should be available; for example on iOS/Android/whatever we have xyz()".

答:
The metadata of a call will only be the bare minimum data required to make the call. So the capabilities of the origination point and the intended endpoint.

Everything else would be added by the network and including any extra data should be stripped to avoid XSS attacks like this one on Who.Is.


答:
My understanding is that the switching that happens in the background uses nothing but the phone number and a short prefix.  The prefix generally contains routing information.

When a switch receives a number, it strips the prefix and parses it, decides on where to route the call and passes it on.  It may or may not add another prefix it expects the next router in the chain to understand.

Given the above, I'm not sure how you could fit metadata into the call.

Source: my experience writing software that manages VOIP dialing campaigns and wholesale route sales.

Title: Is it possible to programmatically attach custom metadata to phone calls?

Body:
I'm trying to determine if it should be possible for a cell phone app to relay custom data along with a phone call. By "should be possible" I mean that I'm not trying to learn how to do it in iOS/Android/whatever, I'm just trying to determine if:

It is permitted by standards: the standards for the metadata that initiates a phone call allow for it to be extended. (I found all kinds of information about high level phone call APIs and CDRs which are kept after a phone call is made, but nothing in the "this is the data header that leaves your phone when you make a call" category).

I can be sure that my custom data will be forwarded intact by the cellular network nodes.

This type of functionality is typically available to apps (from my research: some cellular functionality is implemented by firmware, other functionality has legal issues and its APIs are restricted to privileged users).

In short, what I would ideally like to hear is something along the lines of:
"When you initiate a phone call, the phone generates this header. This part of the header can be used to send custom data, and cellular network nodes won't mess with it. The API for this should be available; for example on iOS/Android/whatever we have xyz()".


问:
What is a Database Environment?
I am going through Relational Database Design by JLM. I have come across words like database, data model, DBMS etc. which I am able to understand. But, I get confused when the author tries to use Database and Database Environment with supposedly different meaning (as per my understanding).

What does Database Environment make up ?
I understand that data model defines relationship of the data whereas DBMS is data model specific and translated data manipulation requests and retrieves data from physical storage device(s). The author defined Database as data and its relationship.

Where does Environment come into picture ?

This is where I got confused :
underlying relationships in a database environment are independent of the data model and therefore also independent of the DBMS you are using

BTW Am I reading the right book to start with, considering am just beginning?

答:
According to Oracle

Database environments encapsulate one or more databases

So an example of dealing with more than one database: one database for the Accounting package, one for the HR system, possibly on the same server (depends on your licencing model) and you're concerned with the interfaces between them that are required to pay your wages...

Title: What is a Database Environment?


问:
Design of high performance file processing web application
I'm trying to design a web app with ability to scale but can't wrap my heads around few concepts. I want to design it right but im not a experienced programmer, i have more of a system engineering background.

Basic architecture look like this:

Web Server -> File processing server -> NoSQL DB -> Search server

So the main scenario is follows:

User uploads a file via site

File is send for processing to a server(python script)

Results of processing is send to NoSQL DB

Results processed by search server and returned to user

We can scale web frontends via load balancing. Something like nginx+apache.

Database scaling is taking care by Cassandra or MongoDB. Search scaling is taking care by elasticsearch or sphinx clustering.

Now I want to be able to add multiple file processing servers in case file uploaded is too big. So I need to somehow split file into chunks and process it simultaneously on multiple nodes plus if node goes down while working it shouldn't affect anything and data must be saved. So I need something else which will be allocating tasks to my file processing servers, balancing load and control execution of tasks.

How to design custom applications for that kind of things? Should I use message queuing?

答:
Computer power is cheap nowadays. Moreover, you don't know yet where the bottleneck will be.

To me, this smells like premature optimization where you worry about performance before even having the load. Perhaps you should just start by making it work, then about scaling it. My 2 cents.

The question is also if you want quick processing time or high throughput. If the processing is really resource/time intensive, it makes sense to split the file, distribute it and merge the results. However, these of course come at a certain cost:
splitting, sending, scheduling outputs, merging, handling part failures. These taks consume resources too and adds lots of complexity. Distributed computation is only suited for appropriate tasks. Computing a single task per server is sometimes more efficient than doing all this stuff.


问:
How can I write these services using SOLID and keep them easy to test?
I am trying to write a couple of classes using SOLID principles and having some trouble.

The problem is quite simple. I have an application that tracks leads. Leads are created when events are raised by the customer - eg file download, registration, page view, etc. A lead can have multiple opportunities - ie opportunities are for different products.

A lead should be created if it doesn't exist.

An opportunity should be created for that lead if it does not exist

The lead score should be incremented based on some event scoring table

The way I wanted to do it was to have a LeadEventHandler class that calls three services TrackLead, TrackOpportunity and IncrementLeadScore. This seems ok, but testing the LeadEventHandler required me to use any-instance which is a code smell.

Note I know I could test the whole chain in LeadEventHandler, but for learning's sake I wanted to test in isolation. I could have injected the dependencies into LeadEventHandler, but this just didn't seem correct.

It would be great if I can let the tests drive my code, but I seem to run into quite a few stumbling blocks.

答:
Speaking purely solid your classes:

```<code>TrackLead, TrackOpportunity
</code>```

Are already fine grained and therefore should be compliant to 'S' single responsibility.

Your class:

```<code>LeadEventHandler
</code>```

Your lead event handler is like a controller to all these smaller processes, so for it to take in dependencies to the TrackLead and Trackopportunity classes makes it compliant to DI but not necessarily 'O' as it is not easily open to extension. To make this easier make sure that your Lead events are stored inside a list in LeadEventHandler that will be enumerated each time an event is received. This way event processors can be added at run time or from an external config. Making it 'O' compliant without changing the code of LeadEventHandler

As far as unit testing is concerned, instances of TrackLead and TrackOpportunity should be mocks/stubs when testing LeadEventHandler because you should not actually be testing their functionality but only that their entry point methods was called

PS: The system you are describing is a very good fit for event based/message bus pattern. Perhaps you can implement something similar

Body:
Speaking purely solid your classes:

TrackLead, TrackOpportunity

Are already fine grained and therefore should be compliant to 'S' single responsibility.

Your class:

LeadEventHandler

Your lead event handler is like a controller to all these smaller processes, so for it to take in dependencies to the TrackLead and Trackopportunity classes makes it compliant to DI but not necessarily 'O' as it is not easily open to extension. To make this easier make sure that your Lead events are stored inside a list in LeadEventHandler that will be enumerated each time an event is received. This way event processors can be added at run time or from an external config. Making it 'O' compliant without changing the code of LeadEventHandler

As far as unit testing is concerned, instances of TrackLead and TrackOpportunity should be mocks/stubs when testing LeadEventHandler because you should not actually be testing their functionality but only that their entry point methods was called

PS: The system you are describing is a very good fit for event based/message bus pattern. Perhaps you can implement something similar


答:
The term "database environment" is not as clearly defined as the other terms you mentioned. So it can have different meanings in different contexts. For example, if refering to Oracle's documentation, it may have the meaning as in the post of @mcottle. In a more general context, it could mean just "the database infrastructure of a company or organization" - the available databases, the available client/server infrastructure, the available database APIs, and so on.

So to understand the citation, you need to clarify the context of that statement. Maybe the author is talking about "underlying relationships of a companies data, independently from how this data is modeled"?

Title: What is a Database Environment?

Body:
I am going through Relational Database Design by JLM. I have come across words like database, data model, DBMS etc. which I am able to understand. But, I get confused when the author tries to use Database and Database Environment with supposedly different meaning (as per my understanding).

What does Database Environment make up ?
I understand that data model defines relationship of the data whereas DBMS is data model specific and translated data manipulation requests and retrieves data from physical storage device(s). The author defined Database as data and its relationship.

Where does Environment come into picture ?

This is where I got confused :
underlying relationships in a database environment are independent of the data model and therefore also independent of the DBMS you are using

BTW Am I reading the right book to start with, considering am just beginning?


问:
When should a trig function, with a degree argument, return -0.0?
In creating trig functions my_sind(d), my_cosd(d), my_tand(d), that used a degree argument rather than a radian one and provided exact answers at multiples of 90, I noticed that the result was sometimes -0.0 rather than 0.0.

```<code>my_sind( 0.0) -->  0.0
my_sind(-0.0) --> -0.0

my_sind(180.0) --> -0.0
my_sind(360.0) -->  0.0
</code>```

sin() and tan() typically return the same sign zero result for a given sign zero input.  It makes sense that my_sin() should match sin() for those inputs.

```<code>my_sind( 0.0) alike sin( 0.0) -->  0.0
my_sind(-0.0) alike sin(-0.0) --> -0.0
</code>```

The question is: for what whole number non_zero_n should/may the result ever return -0.0 for my_sind(180*non_zero_n), my_cosd(180*n + 180), my_tand(180*non_zero_n)?

It is easy enough to code so only f(-0.0) produces -0.0 and be done with it.  Simple wondering if there is any reason to make other f(x) return -0.0 for any other (non-zero) x and the importance of insuring that sign.

Note: This is not a question of why 0.0 vs. -0.0 occurs.  This is not why cos(machine_pi/4) does not return 0.0.  Neither is this a question of how to control the generation of 0.0 or -0.0.  I see it best as a design question.

答:
sin() and tan() typically return the same sign zero result for a given sign zero input

It could be generally true since:

Speed/accuracy. For small enough doubles, the best answer for sin(x) is x. That is, for numbers smaller than about 1.49e-8, the closest double to the sine of x is actually x itself (see the glibc source code for sin()).

Handling of special cases.

A few extraordinary arithmetic operations are affected by zero's sign;
  for example "1/(+0) = +inf" but "1/(-0) = -inf". To retain its
  usefulness, the sign bit must propagate through certain arithmetic
  operations according to rules derived from continuity considerations.

Implementations of elementary transcendental functions like sin(z) and
  tan(z) and their inverses and hyperbolic analogs, though not specified by
  the IEEE standards, are expected to follow similar rules.
  The implementation of sin(z) is expected to reproduce the sign of z
  as well as its value at z = ±O.

(Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit by W. Kahan)

Negatively signed zero echoes the mathematical analysis concept of approaching 0 from below as a one-sided limit (consider 1 / sin(x): the sign of zero makes a huge difference).

EDIT

Considering the second point I'd write my_sind so that:

```<code>my_sind(-0.0) is -0.0
my_sind(0.0) is 0.0
</code>```

The latest C standard (F.10.1.6 sin and F.10.1.7 tan, implementations with a signed zero), specifies that if the argument is ±0, it is returned unmodified.

EDIT 2

For the other values I think it's a matter of approximation. Given M_PI < π:

```<code>0 = sin(π) < sin(M_PI) ≈ 1.2246467991473532e-16 ≈ +0.0
0 = sin(-π) > sin(-M_PI) ≈ -1.2246467991473532e-16 ≈ -0.0
0 = sin(2*π) > sin(2*M_PI) ≈ -2.4492935982947064e-16
0 = sin(-2*π) < sin(-2*M_PI) ≈ 2.4492935982947064e-16
</code>```

So if my_sind provides exact answers at multiples of 180° it can return +0.0 or -0.0 (I don't see a clear reason to prefer one over the other).

If my_sind uses some approximation (e.g. a degree * M_PI / 180.0 conversion formula), it should consider how it's approaching the critical values.

Body:
sin() and tan() typically return the same sign zero result for a given sign zero input

It could be generally true since:

Speed/accuracy. For small enough doubles, the best answer for sin(x) is x. That is, for numbers smaller than about 1.49e-8, the closest double to the sine of x is actually x itself (see the glibc source code for sin()).

Handling of special cases.

A few extraordinary arithmetic operations are affected by zero's sign;
  for example "1/(+0) = +inf" but "1/(-0) = -inf". To retain its
  usefulness, the sign bit must propagate through certain arithmetic
  operations according to rules derived from continuity considerations.

Implementations of elementary transcendental functions like sin(z) and
  tan(z) and their inverses and hyperbolic analogs, though not specified by
  the IEEE standards, are expected to follow similar rules.
  The implementation of sin(z) is expected to reproduce the sign of z
  as well as its value at z = ±O.

(Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit by W. Kahan)

Negatively signed zero echoes the mathematical analysis concept of approaching 0 from below as a one-sided limit (consider 1 / sin(x): the sign of zero makes a huge difference).

EDIT

Considering the second point I'd write my_sind so that:

my_sind(-0.0) is -0.0
my_sind(0.0) is 0.0

The latest C standard (F.10.1.6 sin and F.10.1.7 tan, implementations with a signed zero), specifies that if the argument is ±0, it is returned unmodified.

EDIT 2

For the other values I think it's a matter of approximation. Given M_PI < π:

0 = sin(π) < sin(M_PI) ≈ 1.2246467991473532e-16 ≈ +0.0
0 = sin(-π) > sin(-M_PI) ≈ -1.2246467991473532e-16 ≈ -0.0
0 = sin(2*π) > sin(2*M_PI) ≈ -2.4492935982947064e-16
0 = sin(-2*π) < sin(-2*M_PI) ≈ 2.4492935982947064e-16

So if my_sind provides exact answers at multiples of 180° it can return +0.0 or -0.0 (I don't see a clear reason to prefer one over the other).

If my_sind uses some approximation (e.g. a degree * M_PI / 180.0 conversion formula), it should consider how it's approaching the critical values.


问:
Do any notable C extensions include integer types whose behavior is independent of machine word size
An interesting characteristic of C compared with some other languages is that many of its data types are based upon the word size of the target architecture, rather than being specified in absolute terms.  While this allows the language to be used to write code on machines that might have difficulty with certain types, it makes it very difficult to design code which will run consistently on different architectures.  Consider the code:

```<code>uint16_t ffff16 = 0xFFFF;
int64_t who_knows = ffff16 * ffff16;
</code>```

On an architecture where int is 16 bits (still true of many small microcontrollers) this code would assign a value of 1 using well-defined behavior.  On machines where int is 64 bits, it would assign a value 4294836225, again using well-defined behavior.  On machines where int is 32 bits, it would likely assign a value of -131071 (I don't know if that would be Implementation-Defined or Undefined Behavior).  Even though the code uses nothing except what are nominally supposed to be "fixed-sized" types, the standard would require that two different kinds of compiler in use today would yield two different results, and many popular compilers today would yield a third.

This particular example is somewhat contrived, in that I would not expect in real-world code to assign the product of two 16-bit values directly to a 64-bit value, but it is was chosen as a brief example to show three ways integer promotions may interact with supposedly-fixed-sized unsigned types.  There are some real-world situations where it's necessary for math on unsigned types to be performed according to the rules of mathematical integer arithmetic, others where it's necessary that it be performed according to the rules of modular arithmetic, and some where it really doesn't matter.  A lot of real-world code for things like checksums relies upon uint32_t arithmetic wrapping mod 2³², and upon being able to perform arbitrary uint16_t arithmetic and get results which are, are at minimum, defined as being accurate mod 65536 (as opposed to triggering Undefined Behavior).

Even though this situation would clearly seem undesirable (and will become more so as 64- bit processing becomes the norm for many purposes), the C standards committee from what I've observed prefers to introduce language features which are already used in some notable production environments, rather than inventing them "from scratch".  Are there any notable extensions to the C language which would allow code to specify not just how a type will be stored but also how it should behave in scenarios involving possible promotions?  I can see at least three ways a compiler extension might resolve such issues:

By adding a directive that would instruct the compiler to force certain "fundamental" integer types to be certain sizes.

By adding a directive that would instruct the compiler to evaluate various promotion scenarios as though the machine's types had particular sizes, regardless of the actual sizes of the types on the target architecture.

By allowing means of declaring types with specific characteristics (e.g. declare that a type should behave as a mod-65536 wrapping algebraic ring, regardless of the underlying word size, and should not be implicitly convertible to other types; adding a wrap32 to an int should yield a result of type wrap32 regardless of whether int is larger than 16 bits, while adding a wrap32 directly to a wrap16 should be illegal (since neither could convert to the other).

My own preference would be the third alternative, since it would allow even machines with unusual word sizes to work with a lot of code that expects variables to "wrap" as they would with power-of-two sizes; the compiler may have to add bit-masking instructions to make the type behave suitably, but if code needs a type that wraps mod 65536, it's better to have the compiler generate such masking on machines that need it than to clutter the source code with it or simply have such code by unusable on machines where such masking would be needed.  I'm curious, though, whether there are any common extensions which would achieve portable behavior via any of the above means, or via some means I haven't thought of.

To clarify what I'm looking for, there are a few things; most notably:

While there are many ways by which code could be written so as to ensure desired semantics (e.g. defining macros to perform do math on particular-sized unsigned operands so as to yield a result which explicitly either wraps or does not) or at least prevent undesired semantics (e.g. conditionally-define a type wrap32_t to be uint32_t on compilers where a uint32_t would not get promoted, and figure that it's better for code which requires wrap32_t to fail compilation on machines where that type would get promoted than to have it run and yield bogus behavior), if there is any way of writing the code which would play most favorably with future language extensions, using that would be better than devising my own approach.

I have some pretty solid ideas for how the language could be extended so as to resolve many integer-size issues, allowing code to yield identical semantics on machines with different word sizes, but before I spend any significant time writing them up I'd like to know what efforts in that direction have already been undertaken.

I do not in any way wish to be seen as disparaging the C Standards Committee or the work they have produced; I expect, however, that within a few years it will become necessary to make code work correctly on machines where the "natural" promotion type would 32 bits, as well as those where it would be 64 bits.  I think with some modest extensions to the language (more modest than many of the other changes between C99 nnd C14) it would be possible to not only provide a clean way of efficiently using 64-bit architectures, but in the bargain also facilitate interaction with the "unusual-word-size" machines that the standard has historically bent over backward to support [e.g. making it possible for a machines with a 12-bit char to run code that expects an uint32_t to wrap mod 2³²].  Depending upon the direction future extensions take, I would also expect it should be possible to define macros which would allow code written today to be usable on today's compilers where the default integer types behave as "expected", but also usable on future compilers where integer types would be default behave differently, but where can provide the required behaviors.

答:
As the typical intention of code like this

```<code>uint16_t ffff16 = 0xFFFF;
int64_t who_knows = ffff16 * ffff16;
</code>```

is to perform the multiplication in 64 bits (the size of the variable the result gets stored in), the usual way to get the (platform independent) correct result is to cast one of the operands to force a 64-bit multiplication:

```<code>uint16_t ffff16 = 0xFFFF;
int64_t i_know = (int64_t)ffff16 * ffff16;
</code>```

I have never encountered any C extensions that make this process automatic.

Body:
As the typical intention of code like this

uint16_t ffff16 = 0xFFFF;
int64_t who_knows = ffff16 * ffff16;

is to perform the multiplication in 64 bits (the size of the variable the result gets stored in), the usual way to get the (platform independent) correct result is to cast one of the operands to force a 64-bit multiplication:

uint16_t ffff16 = 0xFFFF;
int64_t i_know = (int64_t)ffff16 * ffff16;

I have never encountered any C extensions that make this process automatic.


答:
The key term here is the term "underlying relationships" [1] which in order to refer to something independent of the DBMS and data model must refer to facts about the objects being modeled. And thus it would seem that "database environment" refers to the context motivating design [2] and use of a database irrespective of whatever means are used to implement the database.

Or to use it in a sentence, "Databasers database in a database environment." The environment extends outside the computer and is the messiness the DBMS and data model are meant to corral.

[1] Note these are relationships not relations.

[2] Note the book is about design.

Title: What is a Database Environment?


问:
How do you stay productive when dealing with extremely badly written code?
I don't have much experience in working in software industry, being self-taught and having participated in open source before deciding to take a job. Now that I work for money, I also have to deal with some unpleasant stuff, which is normal of course.

Recently I was assigned to add logging to a large SharePoint project which is written by some programmer who obviously was learning to code on the job. After 2 years of collaboration, the client switched to our company, but the damage was done, and now somehow I need to maintain this code.

Not that the code was too hard to read. Despite problems—each project has one class with several copy-pasted methods, enormous if nestings, Systems Hungarian, undisposed connections—it's still readable.

However, I found myself absolutely unproductive despite working on something as simple as adding logging. Basically, I just need to go through the code step by step and add some trace calls. However, the idiocy of the code is so annoying that I get tired within 10 minutes of starting. In the beginning, I used to add using constructs, reduce nesting by reversing if's, rename the variables to readable names—but the project is large, and eventually I gave up. I know this is not the task I should be doing, but at least reducing the mess gave me some kind of psychological reward so I could keep going. Now the trick stopped working, and I still have 60% of my work to do.

I started having headaches after work, and I no longer get the feeling of satisfaction I used to get—which would usually allow me to code for 10 hours straight and still feel fresh.

This is not just one big rant, for I really do have an actual question:

Is there a way to stay productive and not to fight the windmills?

Is there some kind of psychological trick to stay focused on the task, instead of thinking “How stupid is that?” each time I see another clever trick by the previous programmer? The problem with adding logging is that I actually have to understand what the code does, and doing so hurts my brain in an unpleasant fashion.

答: Gamify your work.  For example, give yourself 5 points each time you ask a good question about the code, and 10 points each time you answer it.  Give yourself a badge each time you refactor a method or add a new feature.  Once you accrue enough points you get privileges like coffee breaks or biscuits.  Once you complete the whole project you get the privilege to treat yourself to something you really want.</p>


答:
The library doesn't try to distinguish +0 from -0. IEEE 754 worries
  quite a bit about this distinction...I found the functions [in math.h]
  quite hard enough to write without fretting about the sign of nothing.
  -- P.J. Plauger, The Standard C Library, 1992, page 128.

Formally, trig functions should return the sign of zero in accord with the C standard...which leaves the behavior undefined.

In the face of undefined behavior, the principle of least astonishment suggests duplicating the behavior of the corresponding function from math.h. This smells justifiable, while diverging from the behavior of the corresponding function in math.h smells like a way to introduce bugs into exactly the code which depends on the sign of zero.

Title: When should a trig function, with a degree argument, return -0.0?

Body:
In creating trig functions my_sind(d), my_cosd(d), my_tand(d), that used a degree argument rather than a radian one and provided exact answers at multiples of 90, I noticed that the result was sometimes -0.0 rather than 0.0.

```<code>my_sind( 0.0) -->  0.0
my_sind(-0.0) --> -0.0

my_sind(180.0) --> -0.0
my_sind(360.0) -->  0.0
</code>```

sin() and tan() typically return the same sign zero result for a given sign zero input.  It makes sense that my_sin() should match sin() for those inputs.

```<code>my_sind( 0.0) alike sin( 0.0) -->  0.0
my_sind(-0.0) alike sin(-0.0) --> -0.0
</code>```

The question is: for what whole number non_zero_n should/may the result ever return -0.0 for my_sind(180*non_zero_n), my_cosd(180*n + 180), my_tand(180*non_zero_n)?

It is easy enough to code so only f(-0.0) produces -0.0 and be done with it.  Simple wondering if there is any reason to make other f(x) return -0.0 for any other (non-zero) x and the importance of insuring that sign.

Note: This is not a question of why 0.0 vs. -0.0 occurs.  This is not why cos(machine_pi/4) does not return 0.0.  Neither is this a question of how to control the generation of 0.0 or -0.0.  I see it best as a design question.


问:
Alternative to printing debug information to stdout\stderr
I currently have a long running application on an embedded Linux environment and all debug messages are currently being outputted to stdout using printf. This isn't ideal for special users who actually need to use the terminal.

Is there is a way to output to a pseudo-device file, a custom stderr or some type of unhooked stream so a live stream can be viewed if users decide to open it up in a file viewer or is there a better way to go about this?

I have thought about just logging all the debug messages to a file but I want to avoid an issue if the application is left running for days and days on end and the log file is left to fill up to some unmanageable size.

答: The usual solution is to log to a file, and to use log rotation. You can implement the rotation yourself, or use a daemon like logrotate.</p>


答:
Well, you can:

Use log rotation. After given time, close the log, move it away and open new one.

Log to a socket, either UDP or unix domain. In this case the message will be forgotten if you don't have any listener connected.

Put some lightweight syslog daemon there and use syslog(3). There you can configure file with rotation, socket and some other options.

Use some other framework that already implements options like this.

Title: Alternative to printing debug information to stdout\stderr

Body:
I currently have a long running application on an embedded Linux environment and all debug messages are currently being outputted to stdout using printf. This isn't ideal for special users who actually need to use the terminal.

Is there is a way to output to a pseudo-device file, a custom stderr or some type of unhooked stream so a live stream can be viewed if users decide to open it up in a file viewer or is there a better way to go about this?

I have thought about just logging all the debug messages to a file but I want to avoid an issue if the application is left running for days and days on end and the log file is left to fill up to some unmanageable size.


问:
Should one write a custom IndexOutOfRange exception?
In the process of writing a special collection I utilized the already exisiting IndexOutOfRangeException as e.g. a list or array would throw if I were to access an illegal index. Code analysis tells me, however, that this exception should never be thrown by user code, and I fail to see why. If I were to hand out references to this class abstracted by an interface, for example, wouldn't it be a lot better if it just confirmed to the (perceived) norm of throwing the known and beloved IndexOutOfRangeException than a custom IndexNotInRangeException? What's the motivation behind this rule?

答:
IndexOutOfRangeException and NullReferenceException should be thrown by the runtime.

If method, which includes an indexer, validates its parameters, it should throw ArgumentOutOfRangeException and ArgumentNullException instead.

The built in collections, such as List<T> do this:

Exceptions:

ArgumentOutOfRangeException -- index is less than 0. -or- index is equal to or greater than Count.


答:
Supervisor is a popular process manager which has extensive facilities for capturing and storing output from stdout and stderr for managed processes.

Going towards something that's more accessible, you could use Sentry. It's open source, although there are no C++ clients yet I'm aware of, but it boils down to transporting JSON data over HTTP.


答: I think message queuing is your answer, along with discarding the idea that the user should wait for the processing to complete. When the user uploads the file, queue it to a message "processor" which will do the preliminary analysis on it (basically just decide if it's too big and either divert it to a "splitter" queue or simply put it on the regular processing queue). At this point, you should return a token or URL to your user that they can use to access the result when the processing is complete. This way you don't have to worry about timeouts or keeping a session active, and the user has a reference in case they want/need to view the results again without re-processing the file.</p>

Title: Design of high performance file processing web application

Body:
I'm trying to design a web app with ability to scale but can't wrap my heads around few concepts. I want to design it right but im not a experienced programmer, i have more of a system engineering background.

Basic architecture look like this:

Web Server -> File processing server -> NoSQL DB -> Search server

So the main scenario is follows:

User uploads a file via site

File is send for processing to a server(python script)

Results of processing is send to NoSQL DB

Results processed by search server and returned to user

We can scale web frontends via load balancing. Something like nginx+apache.

Database scaling is taking care by Cassandra or MongoDB. Search scaling is taking care by elasticsearch or sphinx clustering.

Now I want to be able to add multiple file processing servers in case file uploaded is too big. So I need to somehow split file into chunks and process it simultaneously on multiple nodes plus if node goes down while working it shouldn't affect anything and data must be saved. So I need something else which will be allocating tasks to my file processing servers, balancing load and control execution of tasks.

How to design custom applications for that kind of things? Should I use message queuing?


问:
Which HTTP verb should I use to trigger an action in a REST web service?
I am implementing a RESTful web service and one of the available actions will be reload. It will be used to reload configurations, cache, etc.

We started with a simple GET to an URI like this: ${path}/cache/reload (no parameters are passed, only the URI is called). I am aware that data should not be modified with a GET request.

Which is the correct verb to use to invoke an action/command in a RESTful web service?

The reload is a command of the REST web service that reload its own cache/configuration/etc. It is not a method that returns information to the client.

Probably what I am trying to do isn't REST, but it is still something that need to be done this way. The reload method was only a real example that makes sense in the scope of the application and most answers focused on it, but in fact, I just needed to know which verb to trigger an action that doesn't do CRUD, but still changes data/state.

I found this detailed asnwer on Stack Overflow abot the subject: https://stackoverflow.com/questions/16877968/

答:
If you want to be RESTful don't think of the verb to carry out an action, think of the state you want the resource to be in after the client has done something.

So using one of your examples above you have an email queue that is sending emails. You want the client to put that email queue into the state of paused or stopped or something.

So the client PUTs a new state to the server for that resource. It can be as simple as this JSON

```<code>PUT http://myserver.com/services/email_service HTTP/1.1
Content-Type: text/json

{"status":"paused"}
</code>```

The server figures out how to get from the current status (say "running") to "paused" status/state.

If the client does a GET on the resource it should return the state it is currently in (say "paused").

The reason to do it this way, and why REST can be so powerful, is that you leave the HOW to get to that state up the server.

The client just says "This is the state you should be in now" and the server figures out how to achieve that. It might be a simple flip in a database. It might require thousands of actions. The client doesn't care, and doesn't have to know.

So you can completely rewrite/redesign how the server does that and the client doesn't care. The client only needs to be aware of the different states (and their representations) of a resource, not any of the internals.

Body:
If you want to be RESTful don't think of the verb to carry out an action, think of the state you want the resource to be in after the client has done something.

So using one of your examples above you have an email queue that is sending emails. You want the client to put that email queue into the state of paused or stopped or something.

So the client PUTs a new state to the server for that resource. It can be as simple as this JSON

PUT http://myserver.com/services/email_service HTTP/1.1
Content-Type: text/json

{"status":"paused"}

The server figures out how to get from the current status (say "running") to "paused" status/state.

If the client does a GET on the resource it should return the state it is currently in (say "paused").

The reason to do it this way, and why REST can be so powerful, is that you leave the HOW to get to that state up the server.

The client just says "This is the state you should be in now" and the server figures out how to achieve that. It might be a simple flip in a database. It might require thousands of actions. The client doesn't care, and doesn't have to know.

So you can completely rewrite/redesign how the server does that and the client doesn't care. The client only needs to be aware of the different states (and their representations) of a resource, not any of the internals.


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答: On a site like this you will find many developers tell you how they have Javascript disabled so you should support progressive enhancement. In reality of the 5% of people who have Javascript disabled, 90% of them are developers and other tech geeks, they are not the general public. Most major sites do not support progressive enhancement. Have you tried to use Facebook without Javascript? They basically say go away.</p>


问:
Cross device testing for web development
Currently, I do not have a fixed process for cross device testing other than randomly asking the people around my co-working space to test my site on whatever device they have on-hand. This is quite a hit-or-miss approach, so I was wondering if anybody had a proper approach to this, as a freelancer. I know some organisations have their own device labs, but that's kind of beyond the budget for a freelancer. </p>

答:
The important part is not to create bugs in the first place! :-)

There are several testing labs, where you can prebook devices for testing by the hour or even quarter hour, some are even offering small time slots for free.

You also could put your website in a container app and send it to apple or samsung for testing the app.

Easiest is to acquire a set of used phones and set up your own lab. Maybe doesn't make sense for one website, but if you do that regularly, it will pay off sooner or later.

If you can't afford that, you are charging too little.

OwnerDisplayName: Hui Jing Chen


答:
Here's a mostly flawless setup for testing your websites :

Cross-browser compatibility :

A good resource prior to implementing your solution is to check Can I Use?, which has compatibility for all the HTML5/CSS3/JS/SVG, etc...

Every time you implement a new feature, test your site in Chrome, Firefox, IE, Safari and Opera (in order of importance). They're all free and can run together on your PC.

There are a few solutions specific for IE, which is always the most annoying browser.

Use the dev tools in the latest version, it lets you emulate IE7+ and will be enough most of the time.

Use BrowserStack in the rare cases where the previous solution isn't enough

More info

Cross-device compatibility:

You can use Chrome's built-in emulator, which exists for exactly this purpose. It can emulate pretty much any phone/tablet possible, and costs nothing. It even emulates the sensors of the device.

Documentation here

Title: Cross device testing for web development

Body: Currently, I do not have a fixed process for cross device testing other than randomly asking the people around my co-working space to test my site on whatever device they have on-hand. This is quite a hit-or-miss approach, so I was wondering if anybody had a proper approach to this, as a freelancer. I know some organisations have their own device labs, but that's kind of beyond the budget for a freelancer. </p>

OwnerDisplayName: xShirase


问:
What is the difference between Encapsulation and High cohesion?
I've looked at encapsulation and cohesion, but they look like the same thing to me.  Isn't an encapsulated object already highly-cohesive?</p>

答:
Encapsulation and High Cohesion are different, but related things.

They both deal with class design but focus on different things.

Encapsulation (aka information hiding) is the idea that one shouldn't expose implementation details - that the class API should not "leak" the internals, making it easier to change said internals later if needed (for instance, exposing an iterator - it may be backed by an array now, but a hash table later on).

High cohesion, on the other end, related to how parts of a class relate to each other, how often they are used together in the class. The more often they are used in conjunction, the higher the cohesiveness of the class.