Auto generate unique IDs using the singleton pattern - oop

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.
In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries.
They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).
The given example:
class IDGenerator
{
private static IDGenerator instance;
private int nextID;
private IDGenerator() { nextID = 1; }
[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}
public int nextId()
{
return nextID++;
}
}
Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.
I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).
But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.
So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?

OK. So the question is how do I ensure that the IDGenerator will not repeat the initial sequence over and over again every time it is resumed, right? As you pointed it out, one solution would be to use a sufficiently strong random generator; the other one would require persisting its state.
So the question becomes: persist or randomize, isn't there any other solution? And the answer is yes.
For instance, every time you resume your generator you could initialize its nextId variable to the current timestamp expressed in seconds (I don't think milliseconds would be necessary.) That way there won't be any repetitions. Of course, you would leave large intervals of unused ids between sessions, but this could be seen as the price you would be glad to pay if you want to keep the generator's code as simple as possible.

public sealed class SingletonIdGenerator
{
private static long _id;
private SingletonIdGenerator()
{
}
public string Id
{
get { return _id++.ToString().Substring(8); }
}
public static SingletonIdGenerator Instance { get { return Nested.instance; } }
private class Nested
{
static Nested()
{
_id = DateTime.Now.Ticks;
}
internal static readonly SingletonIdGenerator instance = new SingletonIdGenerator();
}
}

Related

Creating objects with very many optional fields

I'm trying to recreate Hearthstone cards as objects in Java, but I'm having trouble doing this in a good and efficient way.
All cards have some common properties like a 'name'. But the problem is that there is about 300 cards to generate, and there is about 30 different abilities that each card may or may not have. Now, do I have to create a basic card class with all the possible abilities set to false and then set all its specific ability parameters to true? This approach seems to get very messy with all the getters and all the extra information that some abilities needs to specify... So my question is if there's there a better way to solve this kind of problem?
I would like to create these card objects so that I'm only 'adding' the specific abilities as fields, but I can't figure out how to do this in a good way.
Thankful for help!
Like Dave said, it's a little difficult to be sure what the best solution to your problem is without more context. However, from what I can gather, your problem is a pretty common one. For common problems, programmers often create efficient solutions that can be used over and over again called design patterns.
Design patterns aren't needed in every case, so be careful not to overuse them, but it seems like they could help you here. Both solutions mentioned by Dave may work, but the problem with making each ability an object is that it requires you to make as many classes as you have abilities. Furthermore, if each ability is a simple variable, it may be overkill to create classes for all of them, particularly since so many classes can become difficult to maintain. Although having these abilities inherit from an interface somewhat helps with maintainability, I think an easier solution can probably be found in the builder pattern.
I won't explain it in detail here, but here's a tutorial that seems reasonably simple. It's basic purpose is to
For your particular example it would look something like this:
public class Card
{
private final String name;
private final Ability soundAbility;
private final Ability animationAbility;
private final Ability customMessageAbility;
private final String technology;
// The constructor is private in this case to restrict instantiation to the builder.
private Card(CardBuilder builder)
{
this.name = builder.name;
this.soundAbility = builder.soundAbility;
this.animationAbility = builder.animationAbility;
this.customMessageAbility = builder.customMessageAbility;
this.technology = builder.technology;
}
// Getters
public String getName()
{
return this.name;
}
public Ability getSoundAbility()
{
return this.soundAbility;
}
// ... More getters and stuff ...
#Override
public String toString()
{
String text = "";
text += this.name + ":";
text += "\n\t" + this.soundAbility;
text += "\n\t" + this.animationAbility;
text += "\n\t" + this.customMessageAbility;
text += "\n\tI have the ability of " + this.technology + "!";
return text;
}
// Nested builder class
public static class CardBuilder
{
private final String name;
private Ability soundAbility;
private Ability animationAbility;
private Ability customMessageAbility;
private String technology;
public CardBuilder(String name)
{
this.name = name;
}
public CardBuilder soundAbility(Ability soundAbility)
{
this.soundAbility = soundAbility;
return this;
}
public CardBuilder animationAbility(Ability animationAbility)
{
this.animationAbility = animationAbility;
return this;
}
public CardBuilder customMessageAbility(Ability customMessageAbility)
{
this.customMessageAbility = customMessageAbility;
return this;
}
public CardBuilder technology(String technology)
{
this.technology = technology;
return this;
}
public Card build()
{
return new Card(this);
}
}
}
Then to run the program:
package builderTest;
class BuilderMain
{
public static void main(String[] args)
{
// Initialize ability objects.
Ability a1 = new SoundAbility();
Ability a2 = new AnimationAbility();
Ability a3 = new CustomMessageAbility();
// Build card
Card card = new Card.CardBuilder("Birthday Card")
.soundAbility(a1)
.animationAbility(a2)
.customMessageAbility(a3)
.technology("Flash")
.build();
System.out.println(card);
}
}
The output would be something along the lines of:
Birthday Card:
I have the ability of sound!
I have the ability of animation!
I have the ability of customizing messages!
I have the ability of Flash!
Keep in mind that I'm working without much context, so what you need might be significantly different.
Although previous answers are very good, there is still another way of achieve this Object creation
with very many optional fields
I found myself in similar situation when dealing with DB complexity and Command design pattern. As you know some table columns values are mandatory - some are not. I'm using this Effective Java book
for such cases.
So, useful here is the Consider a builder when faced with many constructor parameters. By doing so, you avoid
first, the Telescoping constructor pattern (does not scale well) - it works, but it is hard to write client code when there are many parameters, and harder still to read it.
second, the JavaBeans Pattern, which is good, but allows inconsistency and mandates mutability. It may be in an inconsistent state partway through its construction and precludes the possibility of making a class immutable too.
The Builder pattern as used simulates named optional parameters as found in Ada and Python.Like a constructor, a builder can impose invariants on its parameters. But it is critical that they be checked after copying the parameters from the builder to the object, and that they be checked on
the object fields rather than the builder fields.
Cheers.

How do I make a well designed validation for a complex collection model?

As input I have a list of Books. As output I expect a SimilarBookCollection.
A SimilarBookCollection has an author, publishYear and list of Books. The SimilarBookCollection can't be created if the author of the books is different or if the publishYear is different.
The solution so far in PHP:
client.php
----
$arrBook = array(...); // array of books
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
$objSimilarBookCollection = new SimilarBookCollection($arrBook);
echo $objSimilarBookCollection->GetAuthor();
}
else {
echo 'Invalid input';
}
SimilarBookCollection.php
---
class SimilarBookCollection() {
public function SimilarBookCollection(array $arrBook) {
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
throw new Exception('Invalid books to create collection');
}
$this->author = $arrBook[0]->GetAuthor();
$this->publishYear = $arrBook[0]->GetPublishYear();
$this->books = $arrBook;
}
public function GetAuthor() {
return $this->author;
}
public function GetPublishYear() {
return $this->publishYear;
}
public function GetBooks() {
return $this->books;
}
}
SimilarBookCollectionValidator.php
---
class SimilarBookCollectionValidator() {
public function IsValid() {
$this->ValidateAtLeastOneBook();
$this->ValidateSameAuthor();
$this->ValidateSameYear();
return $this->blnValid;
}
... //actual validation routines
}
The goal is to have a "special" collection with only books that have the same author and publishYear. The idea is to easily access the repeating information like author or year from the object.
How would you name the SimilarBookCollection? The current name is to
generic. Using a name like SameYearAuthorBookCollection looks a bit
long and strange(if more conditions will be added then name will increase)
Would you use a Validator in SimilarBookCollection constructor using a
defensive programming style?
Would you change the design of the code? If yes how?
It all depends ;)
So if I were to aim for a generic adaptable solution I would do the following:
Validator in constructor
On one hand you are validating twice; that is informative in case of a broken precondition/contract (not giving a valid list), but is double the code to run - for what purpose exactly?
If you want to use this in a system depends on its size, how critical it is, product phase, and likely more criterias.
But then it also is controller logic fitted into a model meaning you are spreading your code around.
I would not put it in the constructor.
Name / Design
I would say keep the BookCollection generic as it is, and have any validation strictly in the controller space, instead of bloating the collection which essentially seems to be an array with the extra field of author.
If you want to differentiate between different collection types use either (multiple) inheritance or some sort of additional field "collectionType"; the former if you expect many derivatives or varying functionality to come (also keeps the logic where different nicely separated).
You could also consider your collection as a set on which you perform queries and for convenience's sake you could maintain some sort of meta data like $AuthorCount = N, $publicationDates = array(...) from which you can quickly derive the collection's nature. This approach would also keep your validator-code minimal (or non-existent), as it'd be implicitly in the collection and you could just do the validation in the controller keeping the effective logic behind it clearly visible.
That would also make it more comfortable for you in the future. But the question really is what you want and need it for, and what changes you expect, because you are supposed to fit your design to your requirements and likely changes.
For your very particular problem the constraints as I understand are as follows:
There is only one collection type class in the system at any given
point in time.
The class's items have several attributes, and for a particular, possibly changing subset of these (called identical attributes), the collection only accepts item lists where the chosen attributes of all items are identical.
The class provides getters for all identical attributes
The class must not be usable in any other way than the intended way.
If not for point 1 I would use a generic base class that is either parametrized (ie you tell it upon instantiation which is the set of identical attributes) or uses multiple inheritance (or in php traits) to compose arbitrary combinations with the needed interfaces. Children might rely on the base class but use a predefined subset of the identical attributes.
The parametrized variant might look something as follows:
class BookCollection {
public function __construct($book_list, $identical_fields=array())
{
if (empty($book_list))
{
throw new EmptyCollectionException("Empty book list");
}
$default = $book_list[0];
$this->ia = array();
foreach($identical_fields as $f)
{
$this->ia[$f] = $default->$f;
}
foreach($book_list as $book)
{
foreach($identical_fields as $f)
{
if ($this->ia[$f] !== $book->$f)
{
throw new NotIdenticalFieldException("Field $f is not identical for all");
}
}
}
$this->book_list = $book_list;
}
public function getIdentical($key)
{
$this->ia[$key];
}
}
final class BC_by_Author extends BookCollection{
public function __construct($book_list)
{
parent::__construct($book_list,array('author'));
}
public function getAuthor(){ $this->ia['author']; }
}
or fooling around with abstract and final types (not sure if it's valid like this)
abstract class BookCollection{
public final function __construct($book_list){...}
abstract public function getIdenticalAttributes();
}
final class BC_by_Author {
public function getIdenticalAttributes(){ return array('author'); }
public function getAuthor(){ return $this->ia['author']; }
}
If you rely on getters that do not necessarily match the field names I would go for multiple inheritance/traits.
The naming then would be something like BC_Field1Field2Field3.
Alternatively or additionally, you could also use exactly the same classname but develop your solutions in different namespaces, which would mean you wouldn't have to change your code when you change the namespace, plus you can keep it short in the controllers.
But because there will only ever be one class, I would name it BookCollection and not unnecessarily discuss it any further.
Because of constraint 4, the white box constraint, the given book list must be validated by the class itself, ie in the constructor.

Which class does a better 'Separation of Concerns'

I have this class, which creates a document and saves it:
public class DocCreator
{
private IDocumentStore _documentStore;
public DocCreator(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public void CreateAndSave()
{
var doc = new Document();
doc.Title = "this is a title";
doc.Content = whateverStream;
doc.Hash = CalculateHash(doc.Content);
//[do more things to create a doc]
_documentStore.PersistToDisk(doc);
}
}
I think it's decent, as the code to save things is hidden in DocumentStore. But we can take it one step further, and remove the call _documentStore.PersistToDisk(doc); to another class, like this:
public class DocCreatorWorkflow
{
private IDocumentStore _documentStore;
public DocCreatorWorkflow(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
public void CreateAndSave()
{
var docCreator = new DocCreator();
var doc = docCreator.Create();
_documentStore.PersistToDisk(doc);
}
}
In the example above I've created another class, which calls two lower classes, and so becomes responsible for the 'workflow'. It might be cleaner, but it also complicates things more. Doesn't it?
Or should I always go for the second option?
I would go with Option 2. You would need to modify the DocCreatorClass, though, since it is no longer responsible for saving it to disk:
public static class DocCreatorClass
{
public static Document Create()
{
Document doc = new Document();
// Property assignment code here.
return doc;
}
}
It would be static so that you would not need to instantiate a DocCreatorClass. I would also create separate functions for Create and Save in the DocCreatorWorkflow class:
public class DocCreatorWorkflow
{
public IDocumentStore _documentStore;
public DocCreateWorkflow(IDocumentStore documentStore)
{
}
public void Document Create()
{
return DocCreatorClass.Create();
}
public void Save(Document doc)
{
_documentStore.PersistToDisk(doc);
}
public void CreateAndSave()
{
Save(Create());
}
}
This way, you don't always have to immediately save to disk the newly-created document. CreateAndSave() would be a convenience function that calls both Save() and Create() inside it, in case your program wants to immediately save a new document often enough.
This type of design is definitely more coding which may come across as more complicated. In the long run, it's easier to look at and maintain because each function does only one thing.
I personally stick with (most of the time, since there may be exceptions) the one class, one responsibility rule. This makes it easier to locate a part of your project when you notice that a functionality doesn't work. When you work on fixing it, you can be rest assured that the rest of your application (the other tasks, thus classes) is untouched. For functions, I like to create them in such a way that within a class, no code blocks will be repeated in two or more different places. This way, you won't have to hunt down all of those identical code blocks to update.
Option two looks better, based on the information available (although there might be other info that may change this judgement).
But, in general, how do you determine which one is better? I think, it is better to start with conceptualizing the concerns, at first, without involving the code. For example, in this case, in my opinion, there are three concerns. 1) creating a document 2) persisting a document 3) performing the logic (some unit of work) that involves creating and saving a document. The key point is, that this third concern is separate from the first two. Neither DocCreator, nor DocumentStore, know that they are being called in this way, or some other way for that matter. Hence, it is not their concern.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.

What is a good way to do multi-row updates in struts (with struts live)?

Without using DynaForm and it's kin.
I would like to use a POJO data transfer object, e.g., Person:
public class Person {
private Long id;
private String firstName;
private String lastName;
// ... getters / setters for the fields
}
In the struts live action form we would have:
public class PersonUpdateForm extends SLActionForm {
String organization;
Person[] persons; // all the people will be changed to this organization; they're names and so forth can be updated at the same time (stupid, but a client might desire this)
// getters / setters + index setters / getters for persons
}
What would the corresponding html:text tags look like in the JSP to allow this? If I switch to a List persons field and use a lazy-loading list (in commons-collections) how would that change thinsg?
There seems to be no good way to do this in struts-1.2(.9?)
All help is greatly appreciated!!! If you need more context let me know and I can provide some.
Okay, I believe I've figured it out! The trick is to have your indexed getter create an element each time the getPersons() method is called by the populate method of BeanUtils. The code is completed yet, but I got a positive looking result. It's 3:30 and I've been stuck on this a while. Nobody seemded to know the answer, which makes me want to smack them in the head with a trout. As for my own ignorance ... I only have them to blame!
public List<Person> getPersons() {
persons.add(new Person()); // BeanUtils needs to know the list is large enough
return persons;
}
Add your indexed getters and setters too, of course.
I remember how I actually did this. You must pre-initialize the persons List above to the maximum size you expect to transfer. This is because the List is first converted to an array, the properties then set on each element of the array, and finally the List set back using setPersons(...). Therefore, using a lazy-loading List implementation or similar approach (such as that show above) will NOT work with struts live. Here's what you need to do in more detail:
private List<Person> persons = new ArrayList<Person>(MAX_PEOPLE);
public MyConstructor() { for(int i = 0; i < MAX_PEOPLE; i++) persons.add(new Person()); }
public List<Person> getPeopleSubmitted() {
List<Person> copy = new ArrayList<Person>();
for(Person p : persons) {
if(p.getId() != null) copy.add(p);
// id will be set for the submitted elements;
// the others will have a null id
}
return copy; // only the submitted persons returned - not the blank templates
}
That's basically what you have to do! But the real question is - who's using struts live anymore?!