It's hard to search for something when you don't know what it's called.
I am buffering a stream of data points with a sort of switchable buffer (imagine a garden hose with a valve): in one state ("true"), I let the data points through to their eventual consumer. In the other state ("false"), I retain those data points in a queue until I transition to the other state, at which point I send those data points to their consumer in order.
Do you have any suggestions for what to name the boolean property that controls this state? I have thought about "on", "buffering", "closed", "delayed", etc and none of them make me particularly happy. I need to come up with a good name before I publish my class to potential "customers" (other programmers here). I can reverse the logic from true <-> false if it makes more semantic sense.
(edit: feel free to just refer to the property as a name without is/get in it. I'm using Java so it will be a Bean-style property with setXXX/isXXX accessors.)
(edit 2: it seems like the property name should, unless it's clearer to do otherwise, reflect the "true" state where data is being letting through transparently without delay.)
IsQueueBufferingEnabled
Or
IsDiverted
(which doesn't expose any implementation details)
hmmm... I'm temporarily using paused, not entirely happy but it's the best I can come up with. (suspended is of similar quality)
HoldBackData?
should reflect the "true" state where data is being letting through transparently without delay
So, floodGatesOpen ? :)
Related
I am reading https://github.com/walterhiggins/ScriptCraft/blob/master/docs/YoungPersonsGuideToProgrammingMinecraft.md and want to try it out with my son.
I see there is a list of events available, though, being new to this mod, I am not sure I can implement what I am thinking of.
Say, I have a territory around my castle, say, square of 300x300 blocks on a plain field. I know the coordinates of the square.
Now, can I track if any mob intersects the bounds from outside to inside?
If it's possible, what's the event I should look for?
Then, can I add some mechanism that would through something in the direction of the mob's position? How could it look like? Or, even just signalling that a mob is in the zone.
Generally, I want to track mobs and do perform some actions for events.
First and foremost, kudos for exploring this with your son.
I wish I could provide exacting details, but my familiarity with ScriptCraft is limited. However, given that is based on Spigot (not Forge, as suggested in the comments), I can provide an answer from that perspective. I’ll leave the nitty-gritty details of accessing POJOs to your expertise with JavaScript.
While player movements fire PlayerMoveEvent events, there is no corresponding event for other entities/mobs. If there were, it would be a matter of checking whether an entity’s location has breached your perimeter and handling it accordingly.
The simplest approach would be to define a function that calls getLivingEntities() on a World, iterator over the list to determine the type of entity and perform whatever actions are desired; say, announce that it has breached your barrier. This function would be registered as a scheduled task with the BukkitScheduler as a repeating synchronous task. I found this example for scheduling a task, though it is for a single delayed asynchronous task.
load(__folder + "../drone/drone.js");
load(__folder + "../core/scriptcraft.js");
Drone.extend("big",function(){
server.scheduler.scheduleAsyncDelayedTask(global.plugin,function(){
(new Drone()).box(1,500,100,500);
print("done");
});
});
On a large server with many entities, the approach would be optimized by accessing each Chunk containing the protected area and retrieving entities contained therein with getEntities().
I have recently encountered some issues with merely passing references to objects/enemies in a game I am making, and am wondering if I am using the wrong approach.
The main issue I have is disposing of enemies and objects, when other enemies or players may still have links to them.
For example, if you have a Rabbit, and a Wolf, the Wolf may have selected the Rabbit to be its target. What I am doing, is the wolf has a GameObject Target = null; and when it decides it is hungry, the Target becomes the Rabbit.
If the Rabbit then dies, such as another wolf killing it, it cannot be removed from the game properly because this wolf still has a reference to it.
In addition, if you are using a decoupled approach, the rabbit could hit by lightning, reducing its health to below zero. When it next updates itself, it realises it has died, and is removed from the game... but there is no way to update everything that is interested in it.
If you gave every enemy a unique ID, you could simply use references to that instead, and use a central lookup class that handled it. If the monster died, the lookup class could remove it from its own index, and subsequently anything trying to access it would be informed that it's dead, and then they could act accordingly.
Any thoughts on this?
One possible approach is to have objects register an interest with the object they're tracking. So the tracked object can inform the trackers of state changes dynamically. e.g. the Wolf registers with the Rabbit (that has a list of interested parties), and those parties are notified by the Rabbit whenever there's a state change.
This approach means that each object knows about its clients and that state is directly tied to that object (and not in some third-party manager class).
This is essentially the Observer pattern.
You approach sounds reasonable, why not? Registering all your objects in a hashmap shouldn't be too expensive. You could then have sort of an event bus where objects could register for different events.
Other than that, there is another approach coming to my mind. You could have the rabbit expose the event directly and have the wolf register on it.
The second approach is appealing for it's simplicity, however it will to some extend couple the event publishers to the subscribers. The first approach is technically more complex but has the benefit of allowing other kind of lookups too.
In practice I hardly ever find situations where I ever need to hold a reference or pointer to game objects from other game objects. There are a few however, such as the targeting example you give, and in those situations that's where unique ID numbers work great.
I suppose you could use the observer pattern for such things to ensure that references get cleared when necessary, but I think that will start to get messy if you need more than 1 reference per object, for example. You might have a target gameobject, you might have gameobjects in your current group, you might be following a gameobject, talking to one, fighting one, etc. This probably means your observing object needs to have a monolithic clean-up function that checks all the outgoing object references and resets them.
I personally think it's easier just to use an ID and validate the object's continued existence at the point of use, although the price is a bit of boilerplate code to do that and the performance cost of the lookup each time.
References only work while design stays monolithic.
First, passing references to other modules (notably, scripting) leads to security and technical problems.
Second, if you want to extend existing object by implementing some behavior and related properties in a new module - you won't have a single reference for all occasions.
We have two domain types: Users and Locations.
We have a method on the LocationRepository: GetUserLocations().
The existing implementation:
var user = UserRepository.GetUser(userId);
var locations = LocationRepository.GetUserLocations(userId);
To me it makes more sense to retrieve the locations associated with a user from the User type i.e.:
var user = UserRepository.GetUser(userId);
var locations = user.GetLocations();
I think the latter implementation reads more cleanly and as an API client I have to deal with fewer types (i.e. the LocationRepository is not required). On the other hand, there will be more code to maintain as I have to write the "facade" to the LocationRepository.
Should I act on my instinct and create a facade on the User type to the LocationRepository, or should I be happy with the status quo and live with a sequence diagram that "feels" wrong to me (i.e. retrieval of the location information feels like it is being retrieved from the wrong "point of view")?
I would approach this from a perspective of maintainability. I agree that doing it with the facade on LocationRepository would "feel right", and would probably make the code slightly more readable.
The tradeoff, as you said, would be more code to maintain. But how much code are we talking about? Is it a lot, and would you have to update it often? Or can you write it once and forget it, and have it be easily unit testable? If it's the former, just swallow it, go with the current implementation, and remind yourself it doesn't really affect functionality. If it's the latter, it might be worth putting in the effort for that good feeling and more readable code elsewhere.
It is surely possible to model our stuff something like this:
Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
.Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
.OfType<User>().CreateNew("John Doe");
Maybe the repository instances should not be visible to the "end developer" and be encapsulated in the model.
However, because we might not have easy access to the Universe.Instance, we do need one or more "entry points" to where to actually get any data from.
UPDATE:
I think on the one hand it should be a goal to keep the number of there "repository facade entry points" as low as possible because that comes closer to the real world, as there is supposed to be only one "Bing Bang" where everything comes from and which spawned all existing data ultimately ;-) ... That said, on the other hand of course today's systems are always big compromises which we have to make, because the ability to model the real world is limited, there are performance implications and so on...
One way you can go in your concrete example however is to use your repositories for always retrieving fresh data, as in:
LocationRepository.Instance.GetUserLocations(userId);
...whereas you use your User model class to hold the result in a property, as in:
var locations = myUser.Locations;
This property would use lazy load technique to load the data from the LocationRepository at first demand and then hold the result. This communicates that the locations are only loaded once, which makes things for developers who use your library easier. You can then decide if you want to make the LocationRepository.GetUserLocation(userId) also visible to the end developer or not. Keep in mind that when going that route you will also need to build some kind of implicit as well as explicit refresh mechanism and lifetime management.
This over-all approach has proven to be very useful for me. However, the async world of Silverlight et ál now adds some new caveats, as such properties cannot be refreshed instantly and synchronously with a new value in one line of code anymore. When we request a refresh, we now have to leverage binding techniques and/or use a callback to then be able to further process the refreshed value.
All in all, the ultimate goal I believe still would be to see for example a UserRepository just as another regular domain type, apparently with the responsibility to create new single User instances and add them to the storage of users, as well as to provide filtered views (queries) on all available users. It would be acceptable that myUser.Locations as well as myLocations.ByUser["John Doe"] hold a reference to the same result. This UserRepository could then merely be a property of another class responsible for holding it, like CompanyStaff for example. Carrying that idea further is what brought me to that Universe.Instance thing. ;-)
On page 175, there is an example of Chocolate Boiler class. Something like this:
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
public ChocolateBoiler {
empty = true;
boiled = false;
}
// and then three methods to fill, drain and boil which changes the
// status of these two flag depending of situation
}
In section "brain power" they ask a question "How might things go wrong if more than one instance of ChocolateBoiler is created in an application?"
I'm not sure what's the problem with this class. Why do we introduce a singleton pattern here? These two flags are not static and so one per instance. So how creating more than one instance can mess things up?
The question isn't about making an instance of an object.
It's about the confusion caused by having two instances of the object, both of which purport to have the status of the ChocolateBoiler.
If some Object (for example, Cooker) thinks it has the status of the ChocolateBoiler, and some other Object (for example, Recipe) things it has the status of the ChocolateBoiler, what happens now?
Since the variables are instance variables, the ChocolateBoiler objects won't agree on the status of the ChocolateBoiler. Now what happens?
It's only a problem if there only can be one ChocolateBoiler, and if there only can be one, it should be a singleton.
I believe in that example you only had only ONE Chocolate boiler. And so you should only be able to create one instance of the object representing it. If you were allowed to create multiple instances, you would then perhaps issue the command if (boiler.hotEnough()) boiler.stop() somewhere in you system and would be surprised that although the boiler is already way too hot, it's not stopping because you are talking to some 'dead' instance of a Boiler, which returns hotEnough() : false.
Using the singleton pattern you are making sure that no matter where in your code you say Boiler.getInstance() you will get the one and only boiler object there is, and that when you then talk to it, it will do as you would expect.
The entire example of the chocolateboiler in a singleton bothered me a lot while I was reading it.
On a really fundamental level, I don't see why its necessary when you only have one physical thing, to enforce that fact in software. What happens if you get another one? what are you going to do, add the second to the same singleton? make 2 different singletons? a simple global variable would do the job.
IMO, its not the boiler itself that you can only have one thing of , its access to that particular boiler's controls. You can't allow a second person to start making a new batch of chocolate while its already in that process for someone else, or even allow the same person to make a second batch before the first is finished. From that point of view, a simple queueing or batch processing system would do the job. Using another pattern from the book, the command pattern would be a much better way of handling it , as there's only one waitress , and all new orders get queued up until the cook's done with the current food order. (er, if you haven't seen the book, what I just said might not make much sense, sorry)
Maybe I'm just not getting the point. I haven't done much OOP or anything with design patterns before, and I'm losing job opportunities because of it, so I'm reading up on it.
I've just finished a six hour debugging session for a weird UI effect where I found that my favorite framework's implementation of an interface function called "getVisibleRegion" disabled some UI feature (and apparently forgot to restore it).
I've filed a bug with the framework, but this made me think about proper design: under what conditions is it legitimate to have any side-effects on an operation with a name that implies a mere calculation/getting operation?
For those interested in the actual details: I had a report on a bug where my plug-in kept breaking Eclipse's code folding so that the folding bar disappeared and it was impossible to "unfold" or see folded code .
I traced it down to a call to getVisibleRegion() on an ITextViewer whose type represents a source code viewer. Now, ITextViewer's documentation does state that "Viewers implementing ITextViewerExtension5 may be forced to change the fractions of the input document that are shown, in order to fulfill this contract". The actual implementation, however, took this a little too liberally and just disabled projection (folding) permanently, never to bring it back.
The biggest reason I can think of is caching results.
I would say None.
This may be such an edge case that it doesn't even qualify as a side effect, but if the result of the calculation is cached in the object, then that would be acceptable. Even so, it shouldn't make a difference to the caller.
I would say only if it's very obvious that the side effect will occur. Here is a quick example:
MakeMyLifeEasyObject mmleo = new MakeMyLifeEasyObject(x, y, z, default, 12, something);
Object uniqueObjectOne = mmleo.getNewUniqueObject();
Object uniqueObjectTwo = mmleo.getNewUniqueObject();
System.out.println(uniqueObjectOne.getId() == uniqueObjectTwo.getId()); // Prints "false"
Now in my theory here, the MakeMyLifeEasyObject has some internal counter (like a primary key on a DB table). There is a side effect of the get. I can also come up with the idea of something like this:
Object thing = list.getNextObjectAndRemoveFromList();
That would make sense too.
Now the caveat of these is that in both cases, it's just better to rename the method.
The first one would probably be better as createNewUniqueObject(), while in the second a different name (in this case pop()) would be better.
When it's not some semi-contrived example like I gave above, I'd say the ONLY side effects that should be going on is creating/updating some cache if the value takes a long time to create or may be used quite a bit and needs to be sped up.
An example of this would be an object that holds a bunch of strings. You have a method, getThingToPrint() that needs to concatenate a bunch together. You could create a cache when that's called, and that would be a side effect. When you update one of the strings that things are based on, the set would invalidate the cache (or update it).
Something like what you described? Definatly sounds like a bug. I can't think of a situation where that would be a good idea. If that is an intended behavior and not a bug, then it should be renamed to something else (i.e. disableThingAndGetVisibleRegion()).
obj.getBusyDoingStuff()