Implementing record level or field level security in ActiveJDBC - activejdbc

Igor,
I was wondering if you might have some hints as to how I might go about implementing record level, or possibly, field level security using ActiveJDBC. I played around with extending the Model class to override some of the methods from Model. However, it's not a very "elegant" solution and started to become rather messy. I know that your Model class has hooks for certain events, but nothing that seems to stick out to me for modifying behavior. I was able to catch the "set" and "get" calls without too much hacking to implement simple "field level security" type logic, but it became very difficult to overload other methods such as those methods that return a List.
Again, I'm looking more for suggestions on how to do this without actually having to change the Model or LazyList class (though I could go that route as well).
I've been using ActiveJDBC for a number of years now, and it's really been a great framework to build on. Thanks for all your hard work!

Haha, thanks for addressing me directly by name!
We do this all the time, as saving passwords in the database in clear text is not that smart. Usually, we use callbacks for specific models: http://javalite.io/lifecycle_callbacks
What you want to do, is register a callback: http://javalite.io/lifecycle_callbacks#registration-of-external-listeners
or override a method beforeSave on a model, since each model is also an event listener for its events.

Related

Is it OK to create an object inside a function

I work on a class in VBA, that encapsulates downloading stuff with MSXML2.XmlHttp.
There are three possibilities for the return value: Text, XML and Stream.
Should I create a function for each:
aText=myDownloader.TextSynchronous(URL,formData,dlPost,....)
aXml.load myDownloader.XmlSynchronous(URL,formData,dlPost,....)
Or can I just return the XmlHttpObject I created inside the class and then have
aText=myDownloader.Synchronous(URL,formData,dlPost,.....).ResponseText
aXML=myDownloader.Synchronous(URL,formData,dlPost,.....).ResponseXML
In the former case I can set the obj to nothing in the class but have to write several functions that are more or less the same.
In the latter case, I relay on the "garbage collector" but have a leaner class.
Both should work, but which one is better coding style?
In my opinion, the first way is better because you don't expose low level details to a high level of the abstraction.
I did something similar with a web crawler in Java, so I have a class only to manipulate the URL connection getting all the needed data (low level) and a high level class using the low level class that return an object called Page.
You can have a third method that only execute myDownloader.Synchronous(URL,formData,dlPost,.....) and stores the returned object in a private variable and the others method only manipulate this object. This form, you will only open the connection one time.
After much seeking around in the web (triggered by the comment by EmmadKareem) I found this:
First of all, Dont do localObject=Nothing at the end of a method - the variable goes out of scope anyway and is discarded. see this older but enlightening post on msdn
VBA uses reference counting and apart from some older bugs on ADO this seems to work woute well and (as I understand) immediately discards ressources that are not used anymore. So from a performance/memory usage point of view this seems not to be a problem.
As to the coding style: I think the uncomfortable fdeeling I had when I designed this could go away by simply renaming the function to myDownloader.getSyncDLObj(...) or some such.
There seem to be two camps on codestyle. One promotes clean code, which is easy to read, but uses five lines everytime you use it. Its most important prerogative is "every function should do one thing and one thing only. Their approach would probably look something like
myDownloader.URL="..."
myDownloader.method=dlSync
myDownloader.download
aText=myDownloader.getXmlHttpObj.ResponseText
myDownloader.freeResources
and one is OK with the more cluttered, but less lineconsuming
aText=myDownloader.getSyncObj(...).ResponseText
both have their merits both none is wrong, dangerous or frowned upon. As this is a helper class and I use it to remove the inner workings of the xmlhttp from the main code I am more comfortable with the second approach here. (One line for one goal ;)
I would be very interested on anyones take on that matter

Factory Pattern - Is having multiple factories a good idea?

I am designing a system that lets a user assign a specific task to be performed when a button is pressed. The task to be performed can be assigned to all sorts of things. So I have an abstract base class called "ButtonTask", and all other tasks inherit from this base to implement the task to be performed along with the associated data it needs to know. This way I can use polymorphism to abstract away all the specifics, I just call "PerformTask" without having to care about what type it actually is. So far so good.
The actual task itself can be set in may different ways, the user may change the task with a UI menu, the task may be read from a file, and also the task may be set remotely via a network message.
At the moment I have a factory function that will create the correct derived type based on the network message, and return a pointer to the base type. The problem is that the UI menu and the file reading feel like they need their own factory method for object creation, as they are inherently different from one another. Is it generally a good idea to have multiple factories for this kind of problem? I can't really think of another way around this problem but perhaps there's something neater I can do.
The only good reason I see to implement multiple factory methods is if you want to be able to create the objects with different sets of initial attributes, for instance by allowing the caller to specify some attributes and setting default values for others - the equivalent of having multiple public constructors.
If the idea is that the tasks are independent of the way they were initiated (GUI, network, etc), then I don't see a need for separate factory methods. Instead, I would say that one of the duties of the factory is to achieve this very abstraction. In other words, calling the same factory from three different parts of the code is absolutely fine. It is probably a good idea to make the factory method static or to make the factory a singleton object, though.
If on the other hand you have a situation where certain tasks can only ever be initiated from the network and others from the GUI, and only a few can be initiated in all three ways, then it might be worthwhile to rethink the design a bit. You should then consider adding another level of abstract Task classes, eg CommonTask, GuiTask, NetworkTask, FileTask, and have factories for them instead of ButtonTask. This is obviously more complex and whether or not it's worth it depends on the number of task classes and the structure of your code.
What you want to avoid is a situation where users of the factory are aware of which specific subclasses of ButtonTask they can receive from the factory. That's a "false base class" situation, ie one where the base class is not a true abstraction of the whole set of its subclasses, and you get out of it by adding the extra subclass layer as outlined above.
Other than that, you might also want to consider renaming ButtonTask; it sounds like a GUI-only task just from the name.

Avoiding binding objects in OOP

I've read that it's recommended not binding components together since if you remove a part the rest might not function properly. However, I see no alternative to binding objects together when using their methods?
Say I have a security class which checks for malicious input, a logging class that logs errors, custom messages etc., and a comment class that handles user comments.
Now, if I wanted to scan the input coming to the comment class, wouldn't it be wisest calling upon the security class' scanInput() method? Also, if malicious input was found, wouldn't it be good to then log this through the logging class' saveDetails()?
But then, if I removed the security class, then the comment class would get problems, or if I removed the logging class the security class wouldn't know how to log.
I'm trying to improve my design, but I don't think that making every class doing everything is a good idea (it's also common sense) so I could really need a head's up here, plain and simple. Spending hours reading about aggregation and composition didn't really help.
You can reduce your dependence on specific objects by separating the interface from the implementation. For this you can use abstract classes or interface constructs. See also dependency injection.

When to use inheritance?

Me and my friend had a little debate.
I had to implement a "browser process watcher" class which invokes an event whenever the browser that is being watched (let's say Internet explorer) is running.
We created a "Process watcher" class, and here starts the debate:
He said that the constructor should only accept strings (like "iexplore.exe"), and i said we should inherit "Process watcher" to create a "browser watcher" which accepts the currently used browser enum, which the constructor will "translate" it to "iexplore".
he said we should use a util function which will act as the translator.
I know both ways are valid and good, but i wonder whats the pros and cons of each, and what is suitable in our case.
Lately I've been taking the approach of "Keep it simple now, and refactor later if you need to extend it".
What you're doing right now seems pretty simple. You only really have one case that you're trying to handle. So I'd say take the simpler approach for now. In the end, if you never have to make another kind of watcher then you'll avoid the extra complexity. However, code it in a way that will make it easier to refactor later if you need to.
In the future, if you find you need another type of watcher, spend the effort then to refactor it into an inheritance (or composition, or whatever other pattern you want to follow). If your initial code is done right the refactoring should be fairly easy, so you're not really adding much extra work.
I've found this approach works fairly well for me. In the cases where I really didn't need inheritance the code stays simple. But when I really do need it I can add it in without any real problems.
Other things being equal I prefer the simpler solution (a single concrete class which takes a string as a constructor parameter) to the more complicated one (using a base class and a subclass).
Inheritance is appropriate when you want to vary behaviour: if the browser watcher will do something that the ordinary process watcher doesn't. But if you only want to vary the value of the data, then just vary the data.
If you have no other use for ProcessWatcher than to serve as the parent of BrowserWatcher than you shouldn't create it. If other Watchers are being implemented that have shared functionality that can be placed in ProcessWatcher, then you should (both are "isa" relationships so Rob's criterion is met).
It really is as simple as that. Arguing that some day you'll have other watchers is not an argument in favor of creating a separate class. It is a mental tic that you should lose ASAP.
Inheritance should only ever be used to implement an "isa" relationship.
As you can say that a "browser watcher" is a specific instance of a "process watcher" then inheritance is suitable for this architecture.
Hence, for me, having the identity of what you are watching passed through as a part of the construction of the browser watcher implementation of the "process watcher" is definitely the way to go.
Edit: More specifically, inheritance is for when you want to specialise behaviour. For example, most animals make a sound, but you could hope to provide which sound to make in a class called animal, you must wait for the specialisation.
So then we have Horse class providing a "neigh" for its sound, a Dog class providing a "bark" for its sound, etc.
HTH
cheers,
Rob
Depends on what use case you have or what god you follow.
I don't say "inheritance is evil" but generally I follow the principle "Favor composition over inheritance" to avoid excessive class hierarchies.
I agree that in most cases, simplicity over complexity is a good strategy, as long as your simplicity is not too short-sighted (ref. Herms, write code in such a way that you can easily re-factor later).
However, I also know how difficult it can be to shut up that bug in your ear that encourages a more thorough design. If you still want to favor inheritance without necessarily thinking in terms of "base class" and "subclass", you can simply define an interface (ex. IProcessWatcher) which is implemented by ProcessWatcher. When you use the ProcessWatcher object, refer to it in terms of the interface so that if you later decide to create a BrowserWatcher (or any other kind of ProcessWatcher), you can do so without forcing it to descend from ProcessWatcher, as long as it implements the IProcessWatcher interface.
Warning: Proceed with caution. It gets tempting to want to define an interface for every single object, and let's face it, that just ridiculous. =)
Ultimately, you need to find something that you're both comfortable with, since you will both have to maintain this code, and I think this might be a nice compromise, rather than simply "Inheritance or No inheritance".
Good luck!
in a very simple sentence can say:
when you need to use inheritance (subclassing) that subclass has different behaviour (not properties) than super class.

Selecting the Correct View for an Object Type

I've had this problem many times before, and I've never had a solution I felt good about.
Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.
I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.
When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.
The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.
I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.
Thanks in advance.
You need to map your "EditorForm" to a transaction at some point. You have a couple options:
A switch statement...like you, I think this stinks, and scales poorly.
An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.
A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.
In C#, I'd implement a Type -> Form mapper like this:
Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();
typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));
// etc, in this example, I'm populating it by hand,
// in real life, I'd use a key/value pair mapping config file,
// and populate it at runtime.
then, when edit is clicked:
Type formToGet;
if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))
{
Form newForm = (Form)Activator.CreateInstance(formToGet);
}
You probably don't want to tie it to the inheritance tree--that will bind you up pretty good later when you get a slight requirements change.
The relationship should be specified somewhere in an external file. Something that describes the relationship:
Editing AdujustmentTransaction = AdjustmentTransactionEditorForm
Editing IssueTransaction = IssueTransactionEditorForm
With a little bit of parsing and some better language than I've used here, this file could become very generalized and reusable--you could reuse forms for different objects if required, or change which form is used to edit an object without too much effort.
(You might want users named "Joe" to use "JoeIssueTransactionEditorForm" instead, this could pretty easily be worked into your "language")
This is essentially Dependency Injection--You can probably use Spring to solve the problem in more general terms.
Do I miss something in the question? I just ask because the obvious OO answer would be: Polymorph
Just execute Transaction.editWindow() (or however you want to call it), and
overwrite the method in AdjustmentTransaction and IssueTrasaction with the required functionality. The call to element.editWindow() then opens the right dialog for you.
An alternative to the Dictionary/Config File approach would be
1) to define a interface for each of the transaction editors.
2) In your EXE or UI assembly have each of the forms register itself with the assembly that creates the individual transaction.
3) The class controlling the registration should be a singleton so you don't have multiple form instances floating around.
3) When a individual transaction is created it pulls out the correct form variable from the registration object and assigns it do an internal variable.
4) When the Edit method is called it just uses the Show method of the internal method to start the chain of calls that will result in the display of that transacton editor.
This eliminates the need for config files and dictionaries. It continues to separate the UI from the object. Plus you don't need any switch statement
The downside is having to write the interface for each every form in addition to the form itself.
If you have a great deal of different types of editors (dozens) then in that case I recommend that you use the Command Pattern
You have a master command that contains the dictonary recommend by Jonathan. That commands in turns will use that dictornary to execute one of a number of other command that calls the correct form with the correct object. The forms continue to be separate from the object themselves. The forms reside in the Command assembly. In addition you don't have to update the EXE to add another editor only the Command assembly. Finally by putting things inside of Command you can implement Undo/Redo a lot easier. (Implement a Unexecute as well as a Execute)