dimanche 23 juillet 2017

Is this correct demonstration of faulty singleton pattern implementation?

I read about the Singleton Pattern from here http://ift.tt/1juRdSp and it has described some common implementation mistakes. I just want to check if these programs I have written do demonstrate their incorrectness.

In the first program, I have created an inherited class and called the protected constructor of the base class. This allows me to create 2 instances of Singleton.

import java.util.*;
import java.lang.*;
import java.io.*;

class Singleton {
    public static Singleton Instance() {
        if (_instance == null) {
            _instance = new Singleton();
            return _instance;
        }
        return _instance;
    }
    protected Singleton() {}
    private static Singleton _instance = null;
}

class SingletonBasher extends Singleton {
    public SingletonBasher() {

    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Singleton x = new Singleton();
        Singleton y = SingletonBasher.Instance();
        if(x != y)
            System.out.println("fail!");
    }
}

In the second program I have simply created two objects using new operator and this works because the constructor is protected. Had it been private, I would have been forced to use the Instance method which will only allow me to create 1 instance.

import java.util.*;
import java.lang.*;
import java.io.*;

class Singleton {
    public static Singleton Instance() {
        if (_instance == null) {
            _instance = new Singleton();
            return _instance;
        }
        return _instance;
    }
    private Singleton() {}
    private static Singleton _instance = null;
}


class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Singleton x = Singleton.Instance();
        Singleton y = Singleton.Instance();
        if(x != y)
            System.out.println("fail!");
    }
}

Pattern to detect parted files for an AudioBook

I am currently working on audiobook android application, where audios are very large, so they come in parts and media player detects it and shows it as a single item.

For example
File1 Name : some-song-name-here-01.mp3
File2 Name : some-song-name-here-02.mp3
File3 Name : some-song-name-here-03.mp3
File4 Name : some-song-name-here-04.mp3

Now app should show it as a single audio file as
some-song-name-here

What logic should i use to get such files. Or if there is some other better way let me know.

Things i have treid
I searched google and i can't find any sample project or code related to that.

What are some open source Struts2 projects?

What are some good projects with High Code Quality that use Struts 2 only, not Spring and also uses essential design patterns mostly used by industries like MVC, DAO-DTO, breaking large project into modules etc.

Is there any detailed article/post/book which I can use to learn where/why/how to use these design patterns, used in large projects?



Note : This question is somewhat similar to Open source Struts2/Spring/Hibernate projects that have high code quality?

SRP in methods that represent SQL queries

I am working on an app that access a db and now I was wondering what is the best practice here.

Maybe is a stupid question, but then I want to make sure it is stupid:P

I have methods representing queries like this:

Public Function GetCellVposOfTransmitter(transmitter As VPos) As VPos
    Return (From position In Dc.VPos
            Join article In Dc.Art
            On position.ArtID Equals article.ArtID
            Where position.VID = transmitter.VID And position.Pos = transmitter.Pos And article.WGrp = 52 
            Select position).FirstOrDefault()
End Function

Public Function GetPressureTransmittersFromProcessId(processId As Integer) As IQueryable(Of VPos)
    Return From position In Dc.VPos
           Join article In Dc.Art
           On position.ArtID Equals article.ArtID
           Where position.SPos = 0 And position.VID = processId And article.WGrp = 33 
           Select position
End Function

In this case I call GetPressureTransmittersFromProcessId first to get a collection of devices associated to a given process and then for every returned item I call GetCellVposOfTransmitter to get the measuring cell built in each device.

Now every method has only one responsability and is so simple as possible, BUT I query twice the database, and in this case more, since I loop trough the collection and query each time.

I could write a method with a query that returns e.g. a Dictionary(Of Vpos,Vpos) that contains every device as key and the associated cell as value. So I will query only once, but I am breaking (or I am not?) the SRP...

What is the best-practice here? I mean, what has priority here, code or server performance? My app will not be overload any server (lol), but is just to know.

How much business code is ok to have in a Factory?

I'm learning patterns using problems that actual I have. So, sorry for some too basic questions.

I have a Factory that creates four different types of products:

class ProductFactory:
    def product_a(self):
        return ProductA()

    def product_a(self):
        return ProductB()

    def product_a(self):
        return ProductC()

    def product_a(self):
        return ProductD()

But ProductA is a little bit complex. In fact ProductA is built using two different classes because those are different data sources that actual have to be put together in a intricate way to generate an useful ProductA.

So, my doubt:

Is that ok to have my product_a() method in the ProductFactory to be responsible to mess around with those two data sources, do everything necessary and finally build the neat ProductA? Or product_a() is not supposed to know anything about how ProductA is mounted using a considerable business logic?

For example, only a illustration, my ProductA would look something like:

    class ProductFactory:

        def __init__(self, data_source1=None, data_source2=None):
            self.data_source1 = data_source1
            self.data_source2 = data_source2

        def product_a(self):

            formated_data = self.data_source1.do_creepy_stuff()
            messed_data = self.data_source2.mess_a_lot()

            final_data = formated_data.update(messed_data)

            return ProductA(final_data)

        def product_b(self):

            return ProductB()

if __name__ == "__main__":

    data_source1 = DataSource1('my_file')
    data_source2 = DataSource2('my_directory')

    factory = ProductFactory(data_source1, data_source2)

    product = factory.product_a()

In case that idea is ok, would be better to pass the data sources as parameter to the product_a() method or as parameter to the factory constructor (like in example)?

In general... I'm very confused to let the factory having the responsibility to know how to execute methods from those data sources (like data_source1.do_creepy_stuff())... I guess any change in my data sources classes could contaminate my factory.

But at the same moment, I actual have a ProductA that uses to different data sources as its parts AND those data sources have to be manipulated before mounting ProductA, by the simply fact those data sources are also used by other parts of the software that has nothing for to do with products.

So, I'm really working hard to understand the best way to deal with that situation and a factory seem to be the best solution, but... there's those doubts...

Thank you for any help!!

Decorator Pattern from Head First Book wrongfully used?

Currently I am reading "Head First Design Patterns". As you may look on pages 24 and 25 of the PDF here, I have doubt in given example.

Why don't we make something like:

public abstract class Beverage {

String description = "Unknown Beverage";
Double cost;
ArrayList<Topping> toppings;  // allows duplicates


public void addTopping(Topping topping){
toppings.add(topping);
cost+=topping.getCost();
}
getter/setter of description
getter/setter of cost
}



Public class Topping{
 String description;
 double cost;

    getter/setter of description
    getter/setter of cost

}

Then answering questions on page 25:

  • Price changes for condiments will force us to alter existing code

    no they won't we can manipulate cost of the topping by setter.

  • New condiments will force us to add new methods and alter the cost method in the superclass

    no, the method is the same.

  • What if a customer wants a double mocha?

    not a problem

Here we can also add Builder pattern.

Why should you use the decorator pattern in this scenario? Is my solution not enough?

samedi 22 juillet 2017

When using "Table Per Concrete" (TPC) Type, how would corresponding design based on Repository design pattern look like?

I have a "Table Per Concrete" (TPC) Type Database design like in the following picture snapshots UML and ERD diagrams:

(Credit Reference: "Inheritance with EF Code First: Part 3 – Table per Concrete Type (TPC)" http://ift.tt/2eEEzFW ) enter image description here

enter image description here

I am trying to implement code based on the Repository design pattern. However, I'm confused to how I should go about doing it because BillingDetail is an Abstract class, and has Not database table corresponding to it.

How would the UML diagram of the Repositories look like, and what kind of methods would they contain?

In the Business Logic code that gets instances using the Repository entities, wouldn't the following code look Unsophisticated, unrefined and crude:

   if(aBillingDetailInstance is BankAccount)
   {

   } 
   else if (aBillingDetailInstance is CreditCard)
   {


   }