All topics

Software engineering practice

103 questions, 100 with answers.

  1. Which architectural patterns you know?
    • Layered Pattern
    • Microkernel
    • CQRS
    • Event Sourcing
    • Microservices Links
    • https://dzone.com/articles/software-architecture-the-5-patterns-you-need-to-k

    From Java interview (MIT)

  2. What does it mean single responsibility?

    Every module should have one single responsibility. This means two separate concerns/responsibilities/tasks should always be implemented in separate modules. Robert C. Martin defines a “responsibility” as a “reason to change”. If a module has several responsibilities, there are several reasons to change this module—namely the requirements for each responsibility may change. On the other hand a reason to change a module also means that it is the responsibility of the module to implement the aspect that is changed. Links

    • http://www.principles-wiki.net/principles:single_responsibility_principle
    • https://javarush.ru/groups/posts/osnovnye-principy-dizajna-klassov-solid-v-java

    From Java interview (MIT)

  3. What is the difference between facade and proxy/gateway?

    Reviewing Facade in the GoF book and the link in another answer to Martin Fowler's Gateway, it appears that their focus is in opposite directions. Facade provides a simple uniform view of complex internals to (one or more)external clients; Gateway provides a simple uniform view of external resources to the internals of an application. This distinction lets us focus on which is more important in a design : With the Facade, the external system is our customer; it is better to add complexity facing inwards if it makes the external interface simpler. With the Gateway, the internal system is our customer; give it all the help we can, even if the externals are more complex. Links

    • https://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-design-patterns

    From Java interview (MIT)

  4. How can be implemented builder?

    We will configure all of the fields that we want on the builder, and then we'll use the builder to create models. At the same time, we'll remove the public constructor from the class and replace it with a private constructor so that models can only be created via the builder. Links

    • https://dzone.com/articles/design-patterns-the-builder-pattern

    From Java interview (MIT)

  5. What is pattern Visitor?

    The core of this pattern is the Visitor interface. This interface defines a visit operation for each type of ConcreteElement in the object structure. Meanwhile, the ConcreteVisitor implements the operations defined in the Visitor interface. The concrete visitor will store local state, typically as it traverses the set of elements. The element interface simply defines an accept method to allow the visitor to run some action over that element - the ConcreteElement will implement this accept method. Links

    • https://dzone.com/articles/design-patterns-visitor
    • https://refactoring.guru/ru/design-patterns/visitor

    From Java interview (MIT)

  6. What is the issue can be solved by visitor?

    So, while the Visitor may seem a bit strange at first, you can see how much it helps to clean up your code. That's the whole point of this pattern - to allow you seperate out certain logic from the elements themselves, keeping your data classes simple. Links

    • https://dzone.com/articles/design-patterns-visitor
    • https://refactoring.guru/ru/design-patterns/visitor

    From Java interview (MIT)

  7. What can you say about pattern observer?

    Observer is a behavioral design pattern. It specifies communication between objects: observable and observers. An observable is an object which notifies observers about the changes in its state. Links

    • https://www.baeldung.com/java-observer-pattern

    From Java interview (MIT)

  8. Why Dependency Injection is needed?

    Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks). Links

    • https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection

    From Java interview (MIT)

  9. The difference between adapter and decorator?

    Decorator, attach additional responsibilities to an object dynamically.

    Adapter, adapts interface of an existing class to another interface. Links

    • https://stackoverflow.com/questions/42737096/design-patterns-adapter-pattern-vs-decorator-pattern

    Home Page

    From Java interview (MIT)

  10. What is dependency injection?

    Dependency Injection is passing dependency to other objects or framework( dependency injector).

    Dependency injection makes testing easier. The injection can be done through constructor.

    SomeClass() has its constructor as following:

    public SomeClass() {
        myObject = Factory.getObject();
    }
    

    Problem: If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.

    Alternative solution:

    • Passing myObject in as an argument to the constructor
    public SomeClass (MyClass myObject) {
        this.myObject = myObject;
    }
    

    myObject can be passed directly which makes testing easier.

    • One common alternative is defining a do-nothing constructor. Dependency injection can be done through setters. (h/t @MikeVella).
    • Martin Fowler documents a third alternative (h/t @MarcDix), where classes explicitly implement an interface for the dependencies programmers wish injected.

    It is harder to isolate components in unit testing without dependency injection.

    In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.

    From Stack Overflow: asked by AR., answered by wds (CC BY-SA 4.0)

  11. What are MVP and MVC and what is the difference?

    Model-View-Presenter

    In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.

    MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

    Two primary variations

    Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.

    • Pro: maximum testability surface; clean separation of the View and Model
    • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

    Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

    • Pro: by leveraging data binding the amount of code is reduced.
    • Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

    Model-View-Controller

    In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:

        Action in the View
            -> Call to Controller
            -> Controller Logic
            -> Controller returns the View.
    

    One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

    Presentation Model

    Read the rest at the sourceFrom Stack Overflow: asked by Mike Minutillo, answered by Glenn Block (CC BY-SA 4.0)

  12. What is Inversion of Control?

    The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which "implements" and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing direct and/or hard-coded dependencies from your code, to replace them with inject-able dependencies.

    Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using the general term "IoC" instead).

    For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:

    public class TextEditor {
        private SpellChecker checker;
        public TextEditor() {
            this.checker = new SpellChecker();
        }
    }
    

    What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

    public class TextEditor {
        private IocSpellChecker checker;
        public TextEditor(IocSpellChecker checker) {
            this.checker = checker;
        }
    }
    

    In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.

    In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:

    SpellChecker sc = new SpellChecker(); // dependency
    TextEditor textEditor = new TextEditor(sc);
    

    Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature.

    For example, we could inject some improved implementation instead of the default implementation, or, depending on user's needs or settings we could even inject a Spanish spellchecker or German spellchecker.

    Note that just like IoC being the base of many other patterns, above sample is only one of many Dependency-Injection kinds, for example:

    • Constructor Injection.

      Where an instance of IocSpellChecker would be passed to constructor, either automatically or similar to above manually.

    • Setter Injection.

      Where an instance of IocSpellChecker would be passed through setter-method or public property.

    • Service-lookup and/or Service-locator

      Where TextEditor would ask a known provider for a globally-used-instance (service) of IocSpellChecker type (and that maybe without storing said instance, and instead, asking the provider again and again).

    From Stack Overflow: asked by Mike Minutillo, answered by urini (CC BY-SA 4.0)

  13. What are drawbacks or disadvantages of the singleton pattern?

    Paraphrased from Brian Button:

    1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

    2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

    3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

    4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

    From Stack Overflow: asked by Ewan Makepeace, answered by Jim Burger (CC BY-SA 3.0)

  14. Difference between static class and singleton pattern?

    What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.

    The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.

    From Stack Overflow: asked by Jorge Córdoba, answered by Jon Skeet (CC BY-SA 3.0)

  15. What is the difference between MVC and MVVM?

    MVC/MVVM is not an either/or choice.

    The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.

    For ASP.Net, MVVM is used to two-way bind data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns on the server-side.

    For Silverlight and WPF, the MVVM pattern is more encompassing and can appear to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the ViewModel simply replaced the controller in MVC (as if you could just substitute VM for C in the acronym and all would be forgiven)...

    The ViewModel does not necessarily replace the need for separate Controllers.

    The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly no idea where its data is coming from.

    *Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.

    Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.

    From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind to make XAML editing a more independent task. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.

    The basic MVCVM guidelines we follow are:

    • Views display a certain shape of data. They have no idea where the data comes from.
    • ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
    • Models hold the actual data (various context, store or other methods)
    • Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.

    We also noted that the Sculpture code-gen framework implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.

    Don't assume controllers are made obsolete by View-models.

    I have started a blog on this topic which I will add to as and when I can (archive only as hosting was lost). There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.

    An additional benefit of using an MVCVM model is that only the controller objects need to exist in memory for the life of the application and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.

    Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try to discourage people from replacing controllers with ViewModels.

    From Stack Overflow: asked by Bjorn Reppen, answered by iCollect.it Ltd (CC BY-SA 4.0)

  16. Does functional programming replace GoF design patterns?

    The blog post you quoted overstates its claim a bit. FP doesn't eliminate the need for design patterns. The term "design patterns" just isn't widely used to describe the same thing in FP languages. But they exist. Functional languages have plenty of best practice rules of the form "when you encounter problem X, use code that looks like Y", which is basically what a design pattern is.

    However, it's correct that most OOP-specific design patterns are pretty much irrelevant in functional languages.

    I don't think it should be particularly controversial to say that design patterns in general only exist to patch up shortcomings in the language. And if another language can solve the same problem trivially, that other language won't have need of a design pattern for it. Users of that language may not even be aware that the problem exists, because, well, it's not a problem in that language.

    Here is what the Gang of Four has to say about this issue:

    The choice of programming language is important because it influences one's point of view. Our patterns assume Smalltalk/C++-level language features, and that choice determines what can and cannot be implemented easily. If we assumed procedural languages, we might have included design patterns called "Inheritance", "Encapsulation," and "Polymorphism". Similarly, some of our patterns are supported directly by the less common object-oriented languages. CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor. In fact, there are enough differences between Smalltalk and C++ to mean that some patterns can be expressed more easily in one language than the other. (See Iterator for example.)

    (The above is a quote from the Introduction to the Design Patterns book, page 4, paragraph 3)

    The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.

    What is the command pattern, if not an approximation of first-class functions? :) In an FP language, you'd simply pass a function as the argument to another function. In an OOP language, you have to wrap up the function in a class, which you can instantiate and then pass that object to the other function. The effect is the same, but in OOP it's called a design pattern, and it takes a whole lot more code. And what is the abstract factory pattern, if not currying? Pass parameters to a function a bit at a time, to configure what kind of value it spits out when you finally call it.

    So yes, several GoF design patterns are rendered redundant in FP languages, because more powerful and easier to use alternatives exist.

    But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use.)

    And it works both ways too. As I said, FP has its design patterns too; people just don't usually think of them as such.

    But you may have run across monads. What are they, if not a design pattern for "dealing with global state"? That's a problem that's so simple in OOP languages that no equivalent design pattern exists there.

    We don't need a design pattern for "increment a static variable", or "read from that socket", because it's just what you do.

    Saying a monad is a design pattern is as absurd as saying the Integers with their usual operations and zero element is a design pattern. No, a monad is a mathematical pattern, not a design pattern.

    In (pure) functional languages, side effects and mutable state are impossible, unless you work around it with the monad "design pattern", or any of the other methods for allowing the same thing.

    Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml everyday, and there are no striking differences between the patterns I use in these languages vs the patterns I use when I write in Java.

    Read the rest at the sourceFrom Stack Overflow: asked by Juliet, answered by Stack Overflow is garbage (CC BY-SA 4.0)

  17. What is an efficient way to implement a singleton pattern in Java?

    Use an enum:

    public enum Foo {
        INSTANCE;
    }
    

    Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

    The Right Way to Implement a Serializable Singleton

    public enum Elvis {
        INSTANCE;
        private final String[] favoriteSongs =
            { "Hound Dog", "Heartbreak Hotel" };
        public void printFavorites() {
            System.out.println(Arrays.toString(favoriteSongs));
        }
    }
    

    Edit: An online portion of "Effective Java" says:

    "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

    From Stack Overflow: asked by Riyaz Mohammed Ibrahim, answered by Stephen Denne (CC BY-SA 3.0)

  18. What is the difference between Builder Design pattern and Factory Design pattern?

    With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.

    From Wikipedia:

    • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
    • Builder often builds a Composite.
    • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
    • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.

    Wikipedia entry for factory design pattern: http://en.wikipedia.org/wiki/Factory_method_pattern

    Wikipedia entry for builder design pattern: http://en.wikipedia.org/wiki/Builder_pattern

    From Stack Overflow: asked by Penguen, answered by Adrian Grigore (CC BY-SA 2.5)

  19. Why is __init__() always called after __new__()?

    Use __new__ when you need to control the creation of a new instance.

    Use __init__ when you need to control initialization of a new instance.

    __new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.

    In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.

    In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

    From April 2008 post: When to use __new__ vs. __init__? on mail.python.org.

    You should consider that what you are trying to do is usually done with a Factory and that's the best way to do it. Using __new__ is not a good clean solution so please consider the usage of a factory. Here's a good example: ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ Recipe.

    From Stack Overflow: asked by Dan, answered by mpeterson (CC BY-SA 4.0)

  20. What are the differences between Abstract Factory and Factory design patterns?

    The Difference Between The Two

    The main difference between a "factory method" and an "abstract factory" is that the factory method is a method, and an abstract factory is an object. I think a lot of people get these two terms confused, and start using them interchangeably. I remember that I had a hard time finding exactly what the difference was when I learnt them.

    Because the factory method is just a method, it can be overridden in a subclass, hence the second half of your quote:

    ... the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

    The quote assumes that an object is calling its own factory method here. Therefore the only thing that could change the return value would be a subclass.

    The abstract factory is an object that has multiple factory methods on it. Looking at the first half of your quote:

    ... with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition ...

    What they're saying is that there is an object A, who wants to make a Foo object. Instead of making the Foo object itself (e.g., with a factory method), it's going to get a different object (the abstract factory) to create the Foo object.

    Code Examples

    To show you the difference, here is a factory method in use:

    class A {
        public void doSomething() {
            Foo f = makeFoo();
            f.whatever();   
        }
        protected Foo makeFoo() {
            return new RegularFoo();
        }
    }
    class B extends A {
        protected Foo makeFoo() {
            //subclass is overriding the factory method 
            //to return something different
            return new SpecialFoo();
        }
    }
    

    And here is an abstract factory in use:

    class A {
        private Factory factory;
        public A(Factory factory) {
            this.factory = factory;
        }
        public void doSomething() {
            //The concrete class of "f" depends on the concrete class
            //of the factory passed into the constructor. If you provide a
            //different factory, you get a different Foo object.
            Foo f = factory.makeFoo();
            f.whatever();
        }
    }
    interface Factory {
        Foo makeFoo();
        Bar makeBar();
        Aycufcn makeAmbiguousYetCommonlyUsedFakeClassName();
    }
    //need to make concrete factories that implement the "Factory" interface here
    

    From Stack Overflow: asked by Silverbolt, answered by Tom Dalling (CC BY-SA 4.0)

  21. What's an Aggregate Root?

    In the context of the repository pattern, aggregate roots are the only objects your client code loads from the repository.

    The repository encapsulates access to child objects - from a caller's perspective it automatically loads them, either at the same time the root is loaded or when they're actually needed (as with lazy loading).

    For example, you might have an Order object which encapsulates operations on multiple LineItem objects. Your client code would never load the LineItem objects directly, just the Order that contains them, which would be the aggregate root for that part of your domain.

    From Stack Overflow: asked by Dinah, answered by Jeff Sternal (CC BY-SA 2.5)

  22. When would you use the Builder Pattern?

    Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

    As Joshua Bloch states in Effective Java, 2nd Edition:

    The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

    We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

    Pizza(int size) { ... }        
    Pizza(int size, boolean cheese) { ... }    
    Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
    Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
    

    This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

    One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

    Pizza pizza = new Pizza(12);
    pizza.setCheese(true);
    pizza.setPepperoni(true);
    pizza.setBacon(true);
    

    The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

    The better alternative is to use the Builder Pattern.

    public class Pizza {
      private int size;
      private boolean cheese;
      private boolean pepperoni;
      private boolean bacon;
      public static class Builder {
        //required
        private final int size;
        //optional
        private boolean cheese = false;
        private boolean pepperoni = false;
        private boolean bacon = false;
        public Builder(int size) {
          this.size = size;
        }
        public Builder cheese(boolean value) {
          cheese = value;
          return this;
        }
        public Builder pepperoni(boolean value) {
          pepperoni = value;
          return this;
        }
        public Builder bacon(boolean value) {
          bacon = value;
          return this;
        }
        public Pizza build() {
          return new Pizza(this);
        }
      }
      private Pizza(Builder builder) {
        size = builder.size;
        cheese = builder.cheese;
        pepperoni = builder.pepperoni;
        bacon = builder.bacon;
      }
    }
    

    Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

    Pizza pizza = new Pizza.Builder(12)
                           .cheese(true)
                           .pepperoni(true)
                           .bacon(true)
                           .build();
    

    This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

    I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

    From Stack Overflow: asked by Charles Graham, answered by user2628 (CC BY-SA 3.0)

  23. Dependency Injection vs Factory Pattern

    When using a factory your code is still actually responsible for creating objects. By DI you outsource that responsibility to another class or a framework, which is separate from your code.

    From Stack Overflow: asked by Binoj Antony, answered by willcodejavaforfood (CC BY-SA 3.0)

  24. Commonly accepted best practices around code organization in JavaScript

    It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.

    var DED = (function() {
        var private_var;
        function private_method()
        {
            // do stuff here
        }
        return {
            method_1 : function()
                {
                    // do stuff here
                },
            method_2 : function()
                {
                    // do stuff here
                }
        };
    })();
    

    I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.

    From Stack Overflow: asked by hugoware, answered by polarbear (CC BY-SA 2.5)

  25. What is the difference in case of intent and application between these two Patterns?

    With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.

    With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

    From Stack Overflow: asked by user366312, answered by John Feminella (CC BY-SA 4.0)

  26. How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?

    Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.

    • Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.

    • Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.

    • Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.

    • Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.

    • Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Suppose you have a complex concept that requires multiple objects to represent. Making changes to that set of objects is confusing, because you don't always know which object has the method you need to call. That's the time to write a Facade that provides high-level methods for all the complex operations you can do to the collection of objects. Example: a Domain Model for a school section, with methods like countStudents(), reportAttendance(), assignSubstituteTeacher(), and so on.

    From Stack Overflow: asked by Charles Graham, answered by Bill Karwin (CC BY-SA 3.0)

  27. Why is IoC / DI not common in Python?

    I don't actually think that DI/IoC are that uncommon in Python. What is uncommon, however, are DI/IoC frameworks/containers.

    Think about it: what does a DI container do? It allows you to

    1. wire together independent components into a complete application ...
    2. ... at runtime.

    We have names for "wiring together" and "at runtime":

    1. scripting
    2. dynamic

    So, a DI container is nothing but an interpreter for a dynamic scripting language. Actually, let me rephrase that: a typical Java/.NET DI container is nothing but a crappy interpreter for a really bad dynamic scripting language with butt-ugly, sometimes XML-based, syntax.

    When you program in Python, why would you want to use an ugly, bad scripting language when you have a beautiful, brilliant scripting language at your disposal? Actually, that's a more general question: when you program in pretty much any language, why would you want to use an ugly, bad scripting language when you have Jython and IronPython at your disposal?

    So, to recap: the practice of DI/IoC is just as important in Python as it is in Java, for exactly the same reasons. The implementation of DI/IoC however, is built into the language and often so lightweight that it completely vanishes.

    (Here's a brief aside for an analogy: in assembly, a subroutine call is a pretty major deal - you have to save your local variables and registers to memory, save your return address somewhere, change the instruction pointer to the subroutine you are calling, arrange for it to somehow jump back into your subroutine when it is finished, put the arguments somewhere where the callee can find them, and so on. IOW: in assembly, "subroutine call" is a Design Pattern, and before there were languages like Fortran which had subroutine calls built in, people were building their own "subroutine frameworks". Would you say that subroutine calls are "uncommon" in Python, just because you don't use subroutine frameworks?)

    BTW: for an example of what it looks like to take DI to its logical conclusion, take a look at Gilad Bracha's Newspeak Programming Language and his writings on the subject:

    From Stack Overflow: asked by tux21b, answered by Jörg W Mittag (CC BY-SA 4.0)

  28. Singletons vs. Application Context in Android?

    I very much disagree with Dianne Hackborn's response. We are bit by bit removing all singletons from our project in favor of lightweight, task scoped objects which can easiliy be re-created when you actually need them.

    Singletons are a nightmare for testing and, if lazily initialized, will introduce "state indeterminism" with subtle side effects (which may suddenly surface when moving calls to getInstance() from one scope to another). Visibility has been mentioned as another problem, and since singletons imply "global" (= random) access to shared state, subtle bugs may arise when not properly synchronized in concurrent applications.

    I consider it an anti-pattern, it's a bad object-oriented style that essentially amounts to maintaining global state.

    To come back to your question:

    Although the app context can be considered a singleton itself, it is framework-managed and has a well defined life-cycle, scope, and access path. Hence I believe that if you do need to manage app-global state, it should go here, nowhere else. For anything else, rethink if you really need a singleton object, or if it would also be possible to rewrite your singleton class to instead instantiate small, short-lived objects that perform the task at hand.

    From Stack Overflow: asked by Martín Schonaker, answered by mxk (CC BY-SA 3.0)

  29. Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

    I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.

    It seems Helper, Manager, and Util are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.

    You could get particularly purple prosey with the names and go for things like Minder, Overseer, Supervisor, Administrator, and Master, but as I said I prefer keeping it like the framework names you're used to.

    Some other common suffixes (if that is the correct term) you also find in the .NET framework are:

    • Builder
      A type that use some parameters to construct an instance of a special type. Builder is usually a throwaway. It may not even need to allocate a variable.
      If the type needs to repeatedly create objects, please use Factory.
      if the type responsible for create multiple different type objects, please use Factories.
    • Writer
      Write some variable into something.
    • Reader
      Read something as variable.
    • Handler
      Designed to deal with a situation or something.
    • Container
      Can put something into it.

    From Stack Overflow: asked by user60229, answered by Chris S (CC BY-SA 4.0)

  30. How do you implement the Singleton design pattern?

    In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:
    Can any one provide me a sample of Singleton in c++?

    Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.

    class S
    {
        public:
            static S& getInstance()
            {
                static S    instance; // Guaranteed to be destroyed.
                                      // Instantiated on first use.
                return instance;
            }
        private:
            S() {}                    // Constructor? (the {} brackets) are needed here.
            // C++ 03
            // ========
            // Don't forget to declare these two. You want to make sure they
            // are inaccessible(especially from outside), otherwise, you may accidentally get copies of
            // your singleton appearing.
            S(S const&);              // Don't Implement
            void operator=(S const&); // Don't implement
            // C++ 11
            // =======
            // We can use the better technique of deleting the methods
            // we don't want.
        public:
            S(S const&)               = delete;
            void operator=(S const&)  = delete;
            // Note: Scott Meyers mentions in his Effective Modern
            //       C++ book, that deleted functions should generally
            //       be public as it results in better error messages
            //       due to the compilers behavior to check accessibility
            //       before deleted status
    };
    

    See this article about when to use a singleton: (not often)
    Singleton: How should it be used

    See this two article about initialization order and how to cope:
    Static variables initialisation order
    Finding C++ static initialization order problems

    See this article describing lifetimes:
    What is the lifetime of a static variable in a C++ function?

    See this article that discusses some threading implications to singletons:
    Singleton instance declared as static variable of GetInstance method, is it thread-safe?

    See this article that explains why double checked locking will not work on C++:
    What are all the common undefined behaviours that a C++ programmer should know about?
    Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I

    From Stack Overflow: asked by Artem Barger, answered by Loki Astari (CC BY-SA 4.0)

After the last page: 3 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.