Iterator Design Pattern

There are some exceptions in the Design Patterns world when design patterns are explained pretty well. Iterator is one of such patterns. However, there is no surprise in that, since this pattern is very easy to use.

So, what is the purpose of this pattern? Basically, this is used when you want to have some custom collection that might have custom way of sequencing your elements. When you have such custom container, then you can use iterator design pattern.

How to implement this pattern? Well, it is very easy. First of all, you provide the implementation for Iterator:

interface Iterator<T> {
    bool HasNext();
 
    T Next();
}

Then, you implement some container that is able to return the iterator of elements specified:

class Container<T> {
    static Iterator<T> GetIterator() {
       return // Iterator<T> is instantiated as a new object
    }
}

And that is it. It is both easy and simple design pattern. I do not think there is something more to tell about it.

When would you use it directly? Probably, never, since all modern languages have interfaces in place that already have Iterator implemented somehow (e.g. C# has IEnumerable). And these interfaces are being implemented in case you actually need custom way of sequencing your elements in the container.

Adapter Design Pattern

This design pattern is pretty easy to use and understand, so this article is going to be short. First of all, why do we need it at all? Well, the main reason is the following – there are some classes that might implement useful algorithms, but we expect a bit different output out of them. For instance:
1) Legacy shape uses top left coordinates, and then height and width for rectangle. We would like to use top left and bottom left coordinates knowing we are talking about rectangle initially.
2) We have old customer authentication interface which expects different type of Customer class that we use.

In other words, there are lots of reasons why Adapter can and should be used. I will give a sketch of real-world example for the customer authentication. Let us say that old authentication API uses the following class for Customer:

public class APICustomer {
    public Email { get; set; }
    public Password { get; set; }
}

And we use the following class:

public class Customer {
    public UserName { get; set; }
    public Password { get; set; }
}

And now we need some adapter that adapts our Customer to APICustomer. We can implement it in the following way:

public class CustomerAdapter {
    public static APICustomer Adapt(Customer c) {
        // Given the circumstances that all users use example.com as email domain.
        // In the Gmail users' database it might actually be so. However, in a more real-world adoption of APICustomer would be much more difficult or even impossible.
        // Still, this is not a bad example to illustrate use of it.
        return new APICustomer { Email = c.UserName + "@example.com", Password = c.Password };
    }
}

And this is it. Basically, I have introduced a pretty simple class that converts object of Customer to APICustomer object. In other words, it means that Adapter does not have any sort of strict obligations regarding use of it, so Adapter might be almost everything that you use everyday in your programming life. Just think about it.

Singleton Design Pattern

There are some things that people always talk about, they think they know everything about it. But this is actually an indication that something is wrong here. Why? Well, there are lots of ways (wrong ones) to implement Singleton that it raises a question. Is it really useful? How?

I am not going to talk here about if Singleton is a good pattern or not, or how to implement it. I like talking about more difficult ones. And Singleton is really simple. It just ensures that item will get initialized once and only once. How is it done, it depends on the programming language, compiler, even the context (clearly, it is impossible to have Singleton design pattern implementation on two separate devices :)), and lots of other things that can come by.

So, what is the problem actually that Singleton solves? It appears that no problem is being solved. Mostly, more problems ARE INTRODUCED than solved in this way. If you like, you can take a look into this example: https://sourcemaking.com/design_patterns/singleton . Example here is some government or government institution. It looks really “developer friendly” (oh, the irony). However, it is not really a Singleton, since governments can change and they change every term, so how unique is this example… Well, I am unable to comprehend this.

Another popular example for Singleton is logging something for some reason. But why people choose to use Singleton for loggers? I am not sure about that, either. Maybe it is the influence of bad examples for usage of Singleton. Clearly, you can create the logger in the following way (if not, please tell me why):

  1. Introduce ILogger (some interface required for logging).
  2. Introduce Logger that implements ILogger.
  3. Instantiate Logger during app startup or add it to IoC Container.
  4. Add ILogger as dependency everywhere it needs to be used.

However, it becomes a bit of problem when IoC Container is not used (or can not be used just right now), and there are lots of classes that needs logging. So, some people just introduce Logger as singleton. And yes, then it logs everything you want, but this introduces huge code smell that is hard to resolve. Also, it is not unit testable or in order to unit test it you are required to add some magical stuff that other developer who looks just into your unit tests might not know anything about it. And sometimes you might really want to test what actually gets logged. Thus, from my point of view Singleton mostly is used by people who are not tend to refactor their architecture of their software, and they try to use most short-sighted way of thinking. This is when Singleton gets used.

Still, Singleton CAN be useful sometimes. When? In IoC Containers it can be useful. For instance, most of the IoC Containers instantiate objects that are memory location agnostic (and it should be), but sometimes building the infrastructure for the whole app we would like a couple of classes to be non-memory agnostic. For instance, maybe we would like to log all of the activity to RAM first, and then initiate some background thread that would flush all of this data to some storage to make it more efficient. In order to be able to conserve some memory, we might actually want to have a Singleton. However, most of the modern IoC Containers support ability to make class instance as Singleton (e.g. Autofac in the C#), so even in this case you would not need to implement Singleton, since it is done for you already by other developers who suffered all of the implementation pain for you. So, why would you want to suffer again if your goal is to develop some industry level app instead of learning? I think that development of commercial apps and learning should not be coupled too much.

In other words, Singleton has its’ own uses, but all of the modern frameworks take care of that for you mostly, so actually there is no need to implement Singleton for you (unless you are going to implement some framework which is the case pretty rarely today). It is simple and really addictive pattern to use, but if you think you want to use Singleton, you should think about refactoring your code instead, since in this way you are making your code even worse than it is right now.

Object Pool Design Pattern

Object Pool Design Pattern is pretty simple one. However, even here tutorials might fail. Let us take a look into a couple of examples:

  1. https://sourcemaking.com/design_patterns/object_pool
  2. https://www.geeksforgeeks.org/object-pool-design-pattern/

Both of these examples talk about performance like it should be the most important thing for the Object Pool while performance here is really important, but it is taken into consideration from a bit different angle. For instance, let us take a look into examples that Object Pool might actually be useful: Parallelization of jobs being performed. This is probably one and only class where Object Pool is actually useful. You take some tasks, you parallelize them across different threads, and you use Object Pool as a Factory or a provider for these objects. Creation and providing of these objects have nothing to do with performance. If you need something to do with performance in the object level, use Prototype for that, not an Object Pool.

In other words, it is correct to say that Object Pool might give some performance benefits. But it is retrieved through the pattern itself instead of through object creation. And finally, we should treat design patterns as an abstract way of designing our algorithms and systems. So, what actually does Object Pool give us? Well, it gives as a pretty centralized and easy to use API to get the objects we might want to get.

Another problem with the Object Pool is the example itself in the first tutorial. Why do we need always to compare design patterns with something which is completely unrelated to the Software Development? So we would be able to pretend that we understand what is this design pattern, yes? Why not trying to ACTUALLY understand and USE it instead of PRETEND? It would be much better for everyone.

So, let us take a look into the following code:

// First, we define the interface for generic Object Pool.
public interface IObjectPool<T>
{
    T Acquire();
 
    void Release(T node);
 
    void SetMaximumPoolSize(int size);
}
 
// Then, we define some Resource. Let us say it will be some node analysing website URL.
public interface IWebsiteURLAnalysisNode
{
    string Analyse(string url);
}
 
// And finally, we have the Object Pool itself:
public class AnalysisNodePool : IObjectPool<IWebsiteURLAnalysisNode>
{
    private static Semaphore _semaphore = new Semaphore(3, 3);
    private static AnalysisNodePool _instance = new AnalysisNodePool();
    private readonly Stack<IWebsiteURLAnalysisNode> _nodes = new Stack<IWebsiteURLAnalysisNode>();
    private readonly IWebsiteURLAnalysisNodeCreator _creator; // This would be initialized somehow, but for simplicity I am not doing this here.
 
    private AnalysisNodePool()
    {
    }
 
    // Would use some IoC Container (like Autofac), but for simplicity this is not bad. Just make sure not to include this into your real projects. Statics are not good if they can be replaced with non-statics.
 
    static AnalysisNodePool GetInstance()
    {
        return _instance;
    }
 
    public IWebsiteURLAnalysisNode Acquire()
    {
        _semaphore.WaitOne();
 
        if (_nodes.Count == 0)
        {
            return _creator.Create();
        }
 
        return _nodes.Pop();
    }
 
    public void Release(IWebsiteURLAnalysisNode node)
    {
        _nodes.Push(node);
 
        _semaphore.Release();
    }
 
    public void SetMaximumPoolSize(int size)
    {
        _semaphore = new Semaphore(size, size);
    }
}

As you can see, example is pretty real, since semaphore is used (to ensure maximum number of resources would get used at the same time). So, this is the example of how to actually use Object Pool design pattern. But why use it for crawler? Well, the reason here is that we know pretty well that number of sockets can be limited. Theoretically, it can be unlimited, but this would give no real benefit, thus adding abstraction to limit number of them in an easy manner is pretty nice way of thinking here. Still, not sure if this is very necessary for simple website crawler projects.

In other words, if you know that you have limited amount of resources that need to be shared among some other classes, then Object Pool Design pattern can be used. The main reason to use Object Pool is to provide some API of acquiring objects representing limited amount of resources, not efficiency as some examples like to say. Efficiency gains might be here, but this is not the reason.

Factory Method Design Pattern

Actually, this is quite simple pattern. However, there are so many inappropriate examples (toy code, non-understandable and useless ones) and even more cryptic explanations that you can easily get confused and think what is the point in using this design pattern? It contains lots of awful examples where using Factory Method does not show its’ possible and practical purpose in no way. For example, let us take a look into a Book Factory! https://sourcemaking.com/design_patterns/factory_method/php/1

Seriously, am I supposed to use this for some Books? Why? What is so special about the book that the book having different title, publisher or any other attribute that can be represented in a primitive data types, i.e. so special that I am supposed to create a Book Factory? Builder for books? Maybe, since there might be massive amount of attributes I would like to set comfortably and abstract setting them. Using Prototype for the Book itself? For the Book itself no way, but if the source is some remote data source, then Prototype can be useful, so Book can really implement ICloneable. But Factory Method for the Book? Maybe there are some ways, but I tend to simplify most difficult processes in most simplistic way possible, so it would be easier to manage them later. Thus, I think Book should not be used as an example for Factory Method. It is just too misleading from actual purpose of this awesome design pattern.

In order to find a proper example for usage of Factory Method, first we should take a couple of points why it is used. Some of the points mentioned in various resources are the following:

  1. Abstraction of new object creation. Yes, this is correct, and it is extremely useful in the IoC Containers where Factory Method is used in this way. However, IoC Containers for this article is a bit too complex example to get real understanding of Factory Method, thus I will leave it out here.
  2. Some say that way how objects are instantiated (created newly in memory or returned from some cache) should not matter for the client. Well, I am not so sure. Even if client will know that new object gets put somewhere and somehow in the memory, I think no client will know exactly the internals of that. If the “new” operator would be really harmful as some people tend to say, then no Object Oriented Programming Language would have operator “new”. As a client, I might want to write code in a way that does not restrict me in any ways. Or at least I would like to have intuitive enough API to write the code. In any case, it is wrong to assume what other developers want from me as an API developer. I can only assume the most standard needs: intuitive and easy to use API, understandable documentation, practical and useful examples (not some too primitive examples like “Hello, World”). However, I really agree that “new” should be avoided if it is possible to get the result without in a more elegant way. But still it should be used somewhere. We just should find proper place for it, not avoid it.
  3. Abstract logic that would come out of direct composition of two actual objects. And this can be quite a real reason to use Factory Method. For instance, you might have some main class for doing something, then you might have another class which also does something where another class has something that does something, and so on. Providing an interface as a proper closure for such type of logic really helps, since it becomes unit testable.
  4. Another thing that is suggested is to use some static class for the main factory. Actually, it is one of the antipatterns that you can think of. If possible, you should avoid this at any costs. What if I intend to use the factory in some model class that creates different objects based on the input provided? With static classes, I would be unable to write unit tests in isolated manner.
  5. And so many more explanations.

There are so many explanations due to the following reasons:

  1. Some people confuse Factory Method with Factory. They are different. Factory is used to create objects whose classes resolve to the same top level definition (parent/grandparent) based on some input parameters. Some even say it is not a pattern, and just a programming technique. Well, we have in this world lots of grammar purifiers. Probably, there is no exception in the developers’ world. So, what actually Factory is? Yes, it is a software development technique. And what a Design Pattern is? Also, it is some sort of software development technique. Thus, simple Factory is also a proper design pattern, since it is a common way to solve the problem specified. Factory is just not the part of GoG patterns. Maybe because it is so obvious and simple that any developer would think about it out of intuition. Still, I think Design Patterns are much more than GoG classics in today’s world.
  2. Some even confuse Factory Method with Abstract Factory. It is a rare case, but I have seen this in code working on the project a couple of years ago.
  3. And most probably just have not enough knowledge in Mathematics, verbal communication is not good enough regarding extremely important things. In other words, they do not actually understand what the Factory Method is, and just pretend to understand. However, they use it all the time. Which is strange, but it happens so.

Thus, I am going to explain this pattern once and for all not to make any confusions regarding it. It is pretty sad to see so many toy examples that are never going to help. So, what example for the Factory Method can be useful? Document factory method INTEGRATED into some document storage medium might be useful example where there is IDocument interface that gives as FileName (e.g. example.json) and its’ JSON representation. For instance, we might have some byte stream and we want to be able to store it in different document storage formats: DOC, DOCX, PDF, HTML, and so on. Currently, we have no idea how to convert that byte[] stream to PDF, DOC, DOCX, and so on. Maybe we do not even know what to expect in that byte[] stream. So, let us create a base class for storage medium based on these unknowns:

// Product participant.
public interface IDocument
{
    string AsJSON { get; }
 
    string FileName { get; }
}
 
// This has not to be a factory or something. It is just a Creator participant, and that is it.
public abstract class DocumentStorageBase
{
    // This is the factory method we are going to use.
    // This is the main point of Factory Method. You can not know exactly what type of document will get created here, but
    // you know that there will be some fixed interface (a.k.a. Product participant).
    protected abstract IDocument Create(byte[] content);
 
    // Just a simple storage method. We have the interface, the data in it, thus we know how to save it in some file.
    public void Store(byte[] content)
    {
        var document = Create(content);
 
        var fileName = document.FileName;
        var json = document.AsJSON;
 
        // Store the document somewhere.
        // Not implementing here, since I want to show the use for pattern, not implementation. You can think of any implementation you like.
    }
}

Then, let us say we know we will have to be able to store PDF documents. So, we introduce two new classes.

// Concrete Product participant.
public class PDFDocument : IDocument
{
    public string AsJSON { get; set; }
 
    public string FileName { get; set; }
}
 
// Concrete Creator Participant.
public class PDFDocumentStorage : DocumentStorageBase
{
    protected override IDocument Create(byte[] content)
    {
        // Some difficult conversion logic that is able to get PDFDocument object from byte[].
        // This class would definitely include some dependency injection.
        return new PDFDocument();
    }
}

And that is it. This is everything about Factory Method. We covered all of the participants, and I have shown a pretty useful example which can really get benefits from the Factory Method. As you can see, Factory Method is extremely powerful pattern, and can be used in such cases where you know just a resulting interface/base class (a.k.a. Product participant), and you want someone else to create Concrete Product participants (i.e. they are created by Concrete Creator participants). And Creator itself is just an abstract class exposing an API method to override Factory Method which is used to create Concrete Product participants.

To sum up everything, Factory Method can be defined in the following way:

  1. It is a Creational Pattern allowing us to defer responsibility of object creation to the child-level through parent-level abstract method definition.
  2. There are four participants: Product (base interface both Client and API developer agree on), Creator (base class which introduced Product creation Factory Method which is abstract and should be implemented by child classes), Concrete Creator (implements the Factory method), Concrete Product (instance of Product interface created by Concrete Creator).
  3. It is useful when you know nothing about concrete products that might be instantiated, but you have a pretty good idea of the interfaces, and you exactly know what needs to be done. In other words, you know WHAT, but you do not know HOW, yet. Or you just want to leave HOW part for later.

Finally, there are some pretty nice explanations regarding Factory Method, too. At least the following one is the single one I was able to find where at least explanation is nice: https://exceptionnotfound.net/the-daily-design-pattern-factory-method/ . Explanation is short, clear, and from this you can really get the idea HOW to use Factory Method. But not sure about WHY. Example is original maybe, but not very useful from the real-world perspective, since it does not show WHY Factory Method should be used. I can code all of the sandwiches without any of the Design Patterns, and I would not lose anything. However, I would lose massive amount of nerves, time, and lots of other stuff if I would try to code smart Website Crawler by trying to include all of the rules in a single class. Or to create God of Documents (a.k.a. God Object that is able to create and store PDF, DOC, DOCX, HTML, XML, and so many more document formats in a single class). By using Factory Method, I can concentrate on the things I know right now, and do not bother that I might not know right now something, since I will always be able to extend the class without violation of SOLID (especially Single Responsibility and Open/Closed principles), and do not worry too much of some unknowns. That is why Factory Method can be used. But for sandwiches, books, colors, shapes… These examples are inappropriate. No one codes different classes for books if title is different. And if one does, then software design in that project should be very messy.

Abstract Factory Design Pattern

How this pattern is described? Well, according to the following sources, description is somehow vague:

  1. https://sourcemaking.com/design_patterns/abstract_factory : “…lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code”. So, is this pattern about rabbits?
  2. https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm : “super-factory”, “factory of factories”.
  3. https://www.geeksforgeeks.org/abstract-factory-pattern/ : Some creation pattern that is another layer of abstraction over factory pattern.

Does this make anything clear? Of course, NOT. Such explanations are vague, wrong and unclear why Abstract Factory is needed, since it raises simple question that no one asks? Why should I use Abstract Factory at all? Maybe I can use just a Factory? Maybe I can use just “new” and that would be it? In other words, I will never use some design pattern unless it is logically and explicitly proven useful or even unavoidable in order to solve some problem. But it looks like that people use design patterns just to look cool and knowing some stuff about patterns. This way of using some technique is extremely bad programming example which causes lots of over-engineering in the systems which is the same bad thing as under-engineering.

So, I will try to remove the shadows around this pattern. First of all, let us take a look into the structure of this pattern. The structure is pretty simple actually. First of all, we have some interface:

interface IFoo {
    void Bar();
}

Now we have lots of objects implementing interface IFoo which implements method “void Bar()” somehow differently. Why? Because they can. So, let us say we have the following implementations: Foo1, Foo2, Foo3, …, FooN. After that, we have some factory that can produce all of the foos.

interface IFooFactory {
    IFoo GetFoo(string fooType);
}

As you can see, I could have actually introduced concrete factory in advance. But instead, I have decided to introduce an interface for the factory. In this way, I am saying that we can have multiple of factories. Why? Because we do not know in advance if there will be a need for one or more factories. So, it is good to introduce an interface in case we will have to introduce something more. In other words, now we have just to introduce factories for the IFooFactory, and we already have our own Abstract Factory Design Pattern implementation. And that is everything about structure of the Abstract Factory.

In other words, it is really simple. You have just two interfaces you are working around:

interface IFactory {
    ISomeItem Create();
}
 
interface ISomeItem {
    // Contract regarding ISomeItem.
}

After that, you just implement either ISomeItem or IFactory. And that is everything you need to know about Abstract Factory. So, it is actually incorrect to say it is “factory of factories”, since you do not make any of the factories from the client point of view. For some weird reason, lots of tutorials include client as a reference, but why if it’s point of view is not taken into account at all? I am not so sure. Maybe people again pretend that they know what they do not actually at all.

So, then why is it still called as “factory of factories”. Well, it is a bit like that, but the factory itself is produced mostly at the startup of the application or something like that, i.e. there is mostly no point to have interface instantiating a factory (and this also violates SOLID, since complex logic is introduced for more paths than one) in some of the class. In some class, factory is needed at most and that is it. So, basically you would have the following code regarding this pattern:

std::string GetOperatingSystem() {
    #ifdef IS_MAC
    return "mac";
    #elif IS_WIN
    return "win";
    #endif
    return "";
}
 
int main() {
    // It is logical to assume that dialogs, some controls get built really differently on different operating systems due to massive
    // differences in their implementations.
    IViewProvider someNativeDialogProvider = ViewProviderFactory().Get(GetOperatingSystem());
 
    SomeViewClient client(someNativeDialogProvider);
    client.InitializeApp();
 
    return 0;
}
 
// Yes, it is more reasonable to be more abstract here detection of device itself and concentrate on the structure we want to layout for the user.
class SomeViewClient
{
public:
    SomeViewClient(IViewProvider& provider) : m_provider(provider) {}
 
    void InitializeApp()
    {
        m_provider.ListenForUserInput({ "first_name", "last_name" }, [this](const blah& input) {});
        m_provider.OpenMainDialog("My Awesome App", [this]
        {
            m_provider.ShowInputField("first_name", "Enter Your Name");
            m_provider.ShowInputField("last_name", "Enter Your Last Name");
            m_provider.ShowButton("Submit All Data");
        });
    }
 
private:
    IViewProvider& m_provider;
};

I think there Abstract Factory can be used, since buttons, input listeners, fields, dialogs will all be different across the platforms. So, what is the main point for the Abstract Factory? The main points are the following:

  1. Detect some input that you would like to leave out of the logic you implement. For instance, you would like on creation of data items on separate database, separate operating system. It would be not nice to have everything boiler-plated in a single place.
  2. When detecting that input, create the Factory interface that creates another Factory based on that input.
  3. Create all of the Factories you need.
  4. Each Factory should create family of objects that is relevant for the input you have extracted out of the system.

Prototype Design Pattern

When learning design patterns, it is really important to see real-world examples to understand actual use for patterns instead of trying to decrypt learning resources and pretend understanding design pattern just because you have read some examples which would never be thought to be used in the real-world. This problem is extremely visible regarding Prototype Design Pattern. Let us look into the examples below:

  1. https://www.tutorialspoint.com/design_pattern/prototype_pattern.htm
  2. https://www.geeksforgeeks.org/prototype-design-pattern/

What could possibly go wrong? Basically, everything with these sources. What are these guys modeling? Some color, some shape? Even the class for different color is created. Have you ever seen someone that creates a class for the color? How many colors are there? Well, modern displays are able to understand at least 16777215 colors or more. So, are you going to create 16777215 or more classes for each color, so you would be able to use prototype? Then, how many shapes are there. Well, there are circle, square, rectangle, triangle. Then, there are lots of 2D irregular shapes. Then, there are extremely massive amount of 3D shapes. Number of colors in the computers can be finite (but this number is still very huge…), but number of shapes is actually infinite.

So, my point is that these two tutorial about Prototype is inappropriate for people who want to learn how to use Prototype in the real-world. They show no real use for the prototype. The one good thing here from these tutorials is that at least Prototype’s goal is correctly defined – create duplicate objects from already existing object in order to save some performance. Yes, this is the correct approach. But do we really need saving performance in order to create some really simple classes? Through prototype, we could even lose performance, since Prototype adds more abstract layer on top of the simple class. Thus, it might even become an asymptotic problem for us if we are going to use just for simple cases like the examples in the examples mentioned.

So, what would be the real-world example where Prototype can actually save the day? Well, all of the calculations, data extractions which are performance-hungry are good candidates for Prototype abstraction. For instance, one of the real-world example can be Website Crawler where there is a class (let’s call it WebsitePage) that contains both URL and HTML Content. In order to get HTML content, it might take quite a long amount of time (up to 1-2 seconds which can be treated as a long amount of time if you need multiple of such classes), since you have to open some remote connection, read some data. After that, you want just to process the page, and be as much as network independent as possible when you already have the HTML page for the URL you want to have. So, here you can use the Prototype. But how?

In order to use Prototype, you first have to implement ICloneable interface (example below is given in C# dialect):

public interface ICloneable<T> {
    T clone();
}

Method clone() will just create the instance of class ICloneable using class’es already existing data. Let us see an example for the WebsitePage class:

public class WebsitePage : ICloneable<WebsitePage> {
 
    public Url { get; set; }
    public HtmlContent { get; set; }
 
    WebsitePage clone() {
        // Note. If you have pretty complex data class here, you can combine Prototype with Builder just right here.
        // But for simplicity, I am not going to do that here.
        return new WebsitePage
        {
            Url = Url,
            HtmlContent = HtmlContent
        };
    }
}

So, where is the performance bottleneck solved? Nowhere. For now at least. Performance bottlenecks are solved in something that most tutorial creators call “Prototype Registry”. However, this naming is really confusing and completely not understandable. Why do we need some registry? We just want to be able to solve the context-related problem and that is why we would like to use the pattern. For Website Crawler case, it would be just a simple Repository being able to create WebsitePage based on URL (this URL can be treated as ID for our so-called “Prototype Registry”). If you like, you can call it like WebsitePagePrototypeRegistry. Just make sure that it is clear enough whose register/repository it is. So, let us implement it:

public class WebsitePageRepository {
    private readonly Dictionary<string, WebsitePage> _pages = new Dictionary<string, WebsitePage>();
 
    public WebsitePage GetPage(string url) {
        // We can even process url and use some finalized form.
        // E.g. we can assume that "http://example.com/page.html" is the same as "http://example.com/page.html#abc".
 
        // In case we have URL already in cache, we just return existing object from cache, and use it.
        if (_pages.ContainsKey(url))
            return _pages[url].Clone();
 
        // This is the actual operation we want to encapsulate, and which can really be slow.
        // Operations such as color creation and other stuff mentioned in examples explaining Prototype are really worthless.
        using (var webClient = new WebClient())
        {
            string htmlCode = webClient.DownloadString(url);
 
            var websitePage = new WebsitePage
            {
                Url = url,
                HtmlContent = htmlCode
            };
 
            _pages[url] = websitePage;
 
            return websitePage;
    }
}
}

And that is it. We have real-world example showing usage of Prototype. As we can see, “Prototype Registry” is the class that is the most important, since it allows us to achieve actual goal we want to achieve. And we really see here real-world use of Prototype to solve real-world problem.

Generally, there are extremely many inappropriate Design Patterns tutorials with trivial and worthless examples that makes extremely confusing to learn Design Patterns. However, my goal is to fill in this gap, and to make sure that people wanting to learn Design Patterns would be able to learn them in a really efficient and non-confusing way through real-world examples.

Email Verification Library Open-Sourced

I have decided that I will need some reusable code across multiple number of my own PHP based projects. So, it was logical decision to introduce some package, and reuse it. The only decision that I had to make was if it should be open-sourced or not. I have decided that there is nothing secret about it, and it might be really useful for other developers, too. Thus, I have decided to introduce Email Verification Library, and put it not just to GitHub, but also to composer. You can see it here:

  1. https://github.com/vaidotasstrazdas/email-check-api/
  2. https://packagist.org/packages/developernode/email-verify

In other words, I feel that I should add some of my code to open-source community, thus I have introduced the library, and moved to both GitHub and Packagist. Hopefully, developers will like this library.

Builder Design Pattern

Builder is categorized as a Creational Design Pattern. Why is it so? Because it is used to create objects in some way. In what way exactly? This article intends to explain that. If something is unclear to you, please ask it in the comments. The main problem is that there are so many extremely and unnecessarily complex examples that this design pattern (as well as other ones) becomes one of the hard things. However, this should not be so. Builder is pretty easy when you understand what it does.

First of all, we have to know what is the difference between object and class. Object itself is an instance of the class, i.e. some operator (it is called “new” in most of the OOP languages) is able to use a definition of the class (variables, methods), and based on that to assign some space in memory where both data and both instructions are defined. If you want to know more, you should definitely look into Assembly and its’ principles. However, point of this article is to explain Builder.

So, you know pretty basically (understanding can be simple, but in this case it is even correct one) what an object is. So, what is a class? I have already explained that, either. So, to make things clear, I should just repeat the same thing. The class is some definition defining data, data types and methods that an instantiated object will be able to perform. In other words, you can treat a class from a mathematical point of view, i.e. you can treat the class as a set of objects that instantiate from the class defined.

Why do we need to know that? Because Builder itself is also a class, and we should talk about exact definition of the Builder itself. And here we come to even more abstract way of thinking – definition of the class itself. What is it? Well, it is simple. Definition of the class is an interface, and class is the instance of the interface. So, what is the interface for Builder? The most abstract interface for Builder can be written in the following way:

interface IBuilder<T> {
    T build();
}

And that is it. T is some type of the class we want our builder to be able to build.

But why do we need building at all? Can’t we just write everything like that? For instance, we have class called “Customer” with some fields, and we just define everything we need. In that same “Customer”, we define multiple methods setting values, and so on. Actually, we can. And I will show how you can do that. Below is the following code that does exactly that:

class Customer {
    public Field1 { get; set; }
    public Field2 { get; set; }
    public Field3 { get; set; }
    public Field4 { get; set; }
    public Field5 { get; set; }
    public Field6 { get; set; }
    public Field7 { get; set; }
    public Field8 { get; set; }
    public Field9 { get; set; }
    public Field10 { get; set; }
}

How the one would instantiate such a massive class? Well, like this:

var customer = new Customer();
customer.Field1 = "Some value 1";
customer.Field2 = "Some value 2";
customer.Field3 = "Some value 3";
customer.Field4 = "Some value 4";
customer.Field5 = "Some value 5";
customer.Field6 = "Some value 6";
customer.Field8 = "Some value 8";
customer.Field9 = "Some value 9";
customer.Field10 = SHA512(customer.Field8 + customer.Field9);

Oops, we forgot to set Field7. Also, we see that Field10 can be logically deduced from Field8 and Field9, so why are we setting it still here? And what if the algorithm to set the value will change? Well, we are going to rewrite this code all over again. And maybe we will end up in a situation where there is going to be 2-3 places of the same repeating logic. After that, we will invent some method that abstracts all of this logic, and this method basically will be some sort of Builder. So, in any case, even the worst developers that want their code to shine are going to invent Builder itself by themselves. And this is the reason why Builder is a pattern.

So, seeing this use of code we see that Builder is a good Design Pattern for the following purposes:

  1. It allows to abstract data items in the class from the value setting and manipulation methods.
  2. Since Builder is a class, we can use it as an interface somewhere else. Also, we can add multiple dependencies (such as the one as algorithm used in setting the Field10).
  3. Potential API client does not need to worry about internals of setting the class. Client might concentrate just on the data in the class itself and that’s it.
  4. We can guarantee that builder will return the finalized state of the class, i.e. the object that is really correct and integral.

However, there is one “drawback” in the Builder design pattern. By introducing a Builder, you also increase the number of lines of code. However, I would not call it as a drawback. When introducing any of the class, any line of code, you are boosting size of your code base. So, basically the whole programming can be treated as a one big “drawback” if you think that adding more lines to code is a “drawback” by itself.

Finally, how to implement the Builder design pattern? As we saw before, we have an interface for the abstract Builder that is able to build instances of class defined by type T. So, we implement this abstract interface for Customer class:

class CustomerBuilder {
    private var readonly _customer = new Customer();
 
    public Customer build() {
        // Here, we can ensure that _customer will be of finalized state. For instance, we can throw an exception marking that something is not set.
        return _customer;
    }
}

But wait, is that really it? Actually, no. No one is going to use abstract builder interface directly. Most of people are going to instantiate some concrete builder themselves through “new” operator or its’ abstraction called “IoC Containers”. And these concrete builders are going to have pretty solid methods. For instance, we can add the method that sets both Field8 and Field9:

class CustomerBuilder {
    private var readonly _customer = new Customer();
 
    public CustomerBuilder setFields(string field8, string field9) {
        customer.Field8 = field8;
        customer.Field9 = field9;
        customer.Field10 = SHA512(field8 + field9);
 
        return this;
    }
 
    public Customer build() {
        // Here, we can ensure that _customer will be of finalized state. For instance, we can throw an exception marking that something is not set.
        return _customer;
    }
}

There is one important thing. Actually, it is not really important for the Builder design pattern, but it is really comfortable to do so: When adding some setter method, return instance of the Builder itself, so we would be able to chain all of the Builder methods.

And that is it. Builder design pattern implemented. So, when to use it exactly? Basically, use it whenever you feel that you have pretty complex looking class (like 5-10 or more fields), and you might expect that setting values for the fields is going to be painful, and this setting logic can be reused. So, as a general rule, you can make your decision based on answers to these questions:

  1. Does the class have at least five fields? If so, you might want to use Builder.
  2. Can we set values for the class fields based on other field values? If the 1st is yes, and this is yes, then you should definitely use Builder Design Pattern.

Thanks for reading, and I hope that now you really know what is the Builder, how to use it, and when to use it.

How to Crash (Almost) Any Android App Through Autofill Framework

Autofill Framework is one of the things that should have resolved lots of issues regarding password managers or other apps that strive in simplifying the process of filling in the data for the user (https://www.xda-developers.com/android-os-autofill-framework-will-finally-resolve-a-long-standing-lag-issue-with-password-managers/). There were even threats by Google itself that apps who are not going to use Autofill Framework instead of Accessibility Service to fill in the data, are going to be kicked out from the Play Store (https://www.xda-developers.com/google-threatening-removal-accessibility-services-play-store/) . About the latter, I think Google went too far given that Autofill Framework being developed for almost two years still has massive issues, such as being able to kill any other Android app.

This framework is being adopted, but so far Autofill Framework does not cover pretty basic use cases. And there is not just not covering, but through Autofill Framework you can crash other apps. I have even created a ticket for that: https://issuetracker.google.com/u/0/issues/125158212 . In my GitHub repository, you can get the code which demonstrates how to use Autofill Framework to crash other Android apps: https://github.com/vaidotasstrazdas/autofill-crash-demo .

The idea is simple – simulation of dataset being no longer available which might happen due to lots of circumstances. For instance, user logs out, and another user logs in which does not have any data that previous user had. As you can see, use case is really valid, often occuring, but such use case crashes the app you want to autofill. Hopefully, Google will fix this bug, or provide another way to make sure this issue is resolved.