Java class design - class-design

So I have this web application I am making, as of now there is a Database class that handles database functionality queryMovies, updateMovies, and getConnection. Now I want to parse an array of movie titles retrieved from a file directory into addMovies. What would be the most efficient way to add this functionality?
Should I add it in the Database constructor and use an array member variable? another class? in the servlet? Come to think of it I may want to add some functions to file string name retrieval for more modularity... maybe another class would be best. This functionality would always be used for database queries hmmm. hmmm. Some help would be great.

The below can get you started. Remember to code against interfaces so that it is easy to unit test. keep the abstractions focused (Single Responsibility Principle)
public interface FileParser
{
List<Movie> parse(String filePath);
}
public class Movie
{
...
}
public class FileHandler
{
MovieRepository repo=new MovieRepository();
void storeMovies(List<Movie> movies);
}
pubic class MovieRepository
{
//handles CRUD by talking to the DB
}

Related

Why are static GWT fields not transferred to the client?

ConfigProperty.idPropertyMap is filled on the server side. (verified via log output)
Accessing it on the client side shows it's empty. :-( (verified via log output)
Is this some default behaviour? (I don't think so)
Is the problem maybe related to the inner class ConfigProperty.IdPropertyMap, java.util.HashMap usage, serialization or some field access modifier issue?
Thanks for your help
// the transfer object
public class ConfigProperty implements IsSerializable, Comparable {
...
static public class IdPropertyMap extends HashMap
implements IsSerializable
{
...
}
protected static IdPropertyMap idPropertyMap = new IdPropertyMap();
...
}
// the server service
public class ManagerServiceImpl extends RemoteServiceServlet implements
ManagerService
{
...
public IdPropertyMap getConfigProps(String timeToken)
throws ConfiguratorException
{
...
}
}
added from below after some good answers (thanks!):
answer bottom line: static field sync is not implemented/supported currently. someone/me would have to file a feature request
just my perspective (an fallen-in-love newby to GWT :-)):
I understand pretty good (not perfect! ;-)) the possible implications of "global" variable syncing (a dependency graph or usage of annotations could be useful).
But from a new (otherwise experienced Java EE/web) user it looks like this:
you create some myapp.shared.dto.MyClass class (dto = data transfer objects)
you add some static fields in it that just represent collections of those objects (and maybe some other DTOs)
you can also do this on the client side and all the other static methods work as well
only thing not working is synchronization (which is not sooo bad in the first place)
BUT: some provided annotation, let's say #Transfer static Collection<MyClass> myObjList; would be handy, since I seem to know the impact and benefits that this would bring.
In my case it's rather simple since the client is more static, but would like to have this data without explicitely implementing it if the GWT framework could do it.
static variables are purely class variable It has nothing to do with individual instances. serialization applies only to object.
So ,your are getting always empty a ConfigProperty.idPropertyMap
The idea of RPC is not that you can act as though the client and the server are exactly the same JVM, but that they can share the objects that you pass over the wire. To send a static field over the wire, from the server to the client, the object stored in that field must be returned from the RPC method.
Static properties are not serialized and sent over the wire, because they do not belong to a single object, but to the class itself.
public class MyData implements Serializable {
protected String name;//sent over the wire, each MyData has its own name
protected String key;
protected static String masterKey;//All objects on the server or client
// share this, it cannot be sent over RPC. Instead, another RPC method
// could access it
}
Note, however, that it will only be that one instance which will be shared - if something else on the server changes that field, all clients which have asked for a copy will need to be updated

basic info about C# classes and inheriting from other classes

I'd like to write a class which extends the functionality of the MembershipProvider and MembershipUser. But my knowledge in this area is woefully lacking.
My cs file looks something like this:
namespace Mech
{
public class Mechs : MembershipProvider
{
private static Database dbConn = DatabaseFactory.CreateDatabase("main");
public override MembershipUser GetUser(string username, bool userIsOnline)
{
}
}
}
At this point it's complaining about all the abstract members not being implemented. I don't really need to change every single member of membershipProvider, just a handful. So what would be the correct way of doing this?
Take a look at this article at codeguru. You only need to implement what you're going to use, and you can leave the rest throwing NotImplementedExceptions. Additionally, you can extend an existing provider (e.g. SqlMembershipProvider) and override ValidateUser or anything else your heart desires.
As you are inheriting from an abstract class you need to implement all the non-abstract methods and proporties.
You don't necessarily have to change everythingthing . You can just leave them as it after implementation.
You can use VS smart features to save you from lots of typing and the parent class has lots and lots of abstract members and methods.
Click on MembershipProvide , Wait for Intellisences to show you the hint as in below picture:
(Alternatively press Alt+Shift+F10)
Now that's it , you will have your class implementing all the abstract methods and proporties.
So what will happen when you will try to access Field1:
StackOverflow stackOverFlow = new StackOverflow();
String myString = stackOverFlow.Field1;

Reusable Querying in Entity Framework WITHOUT Repository. How?

Let me say, I have come to the conclusion (after a lot of trial) that Repository & Unit of Work when using Entity Framework is just wrong, wrong, wrong and this says why quite well.
But I really hate on those embedded queries. Question is, where can I put them instead if I'm so against a repository, etc? (clean answers only please, examples much appreciated).
I just nuked two projects containing my repositories, unit of work and interfaces with hundreds of files because the payback was nowhere to be seen. I think lots of people, myself included, just jumped on the Repository bandwagon because that's what everybody else was doing but in retrospect, I think it's really a ride to nowhere.
/sigh
Richard
Where do you expect to put them? You have only few choices:
Let them be where they are and use custom extension methods, query views, mapped database views or custom defining queries to define reusable parts
Expose every single query as method on some separate class. The method mustn't expose IQueryable and mustn't accept Expression as parameter = whole query logic must be wrapped in the method. But this will make your class covering related methods much like repository (the only one which can be mocked or faked). This implementation is close to implementation used with stored procedures.
You will do the same as in previous method but instead of placing queries in separate class you will put them as static methods to entity directly. This is much worse testable because static methods cannot be replaced by mocking (it requires more complex testing framework). This is part of active record pattern where each entity is responsible for its loading and saving to database.
Example of custom extension method:
public static IQueryable<TEntity> GetByName(this IQueryalbe<TEntity> query, string name)
where TEntity : IEntityWithName
{
return query.Where(e => e.Name == name);
}
Example of custom class exposing methods:
public class QueryProvider
{
public QueryProvider() {}
public IEnumerable<TEntity> GetByName(IYourContext context, string name)
where TEntity : IEntityWithName
{
return context.CreateObjectSet<TEntity>().Where(e => e.Name == name).ToList();
}
}
Build Reusable, Testable Queries Part 1
This is a blog post I wrote about building reusable queries. Using Extension Methods allows you to build composable queries.
using a pattern like the specification pattern can help you build queries that can be reused or saved (serialized). Further more if you have a double entry system you can execute the same query instance over two different databases.
the following example does not use EF but replace the IEnumerable by an EF context and you get what ou are looking for. parameters are passed in through the constructor.
public class PartialMatchQuery : IModelQuery<string, IEnumerable<string>>
{
private readonly string partial;
public PartialMatchQuery(string partialString)
{
partial = partialString;
}
public IEnumerable<string> Execute(IEnumerable<string> model)
{
return model.Where(s => s.ToLower().Contains(partial));
}
}

asp.net mvc 2 with dynamically generated views

i am trying to build an asp.net mvc 2 app for data entry. I want to generate the views on the forms dynamically so will be using htmlhelpers . What would be the most flexible option for the datasource ? so when i change the database i dont have to actually change the code at all(so i guess EF is not an option)? so no model/controller changes etc. Or i don't have a choice but changing the models in my code?
Well by change database, i assume you mean change dbms, from sql server to oracle for example.
I doubt you'll find a solution to do this without any code changes at all, but you can make things a lot simpler by using interfaces for all you services.
For example
public interface IDataRepository
{
...
}
public class SqlServerDataRepository : IDataRepository
{
...
}
and for testing
public class MockRepository : IDataRepository
{
...
}
and later if you swith databases
public class OracleRepository : IDataRepository
{
...
}
This could then be used simple by referring to interfaces
public class MyService
{
public MyService(IRepository repo)
{
//ctor
{
}
And ideally injecting objects with Inversion of control, Ninject or structuremap for example.
Apologies if this is all already know to you and your looking for something different!

GWT RequestFactory and multiple types

My GWT app has ten different kinds of entities. Right now I use plain old DTOs and transport them over GWT-RPC. This works well for cases like startup - I can pack them all into a single request.
I'm looking at switching to RequestFactory because there are many times throughout the lifetime of the app (30 minutes, on average) when I just have to update one type of entity, and the unifying/bandwidth-saving features of RequestFactory are appealing. BUT: I don't see a way to download all of my initialization data in a single request when the app loads. I don't want to have to make ten requests to fetch all of the init data for my ten entity types.
Is there a way to make a GeneralRequestContext, or something? I'd even be happy with a solution like:
public interface InitDataProxy extends EntityProxy
{
public UserProxy getInitUsers();
public OrganizationProxy getInitOrganizations();
...
}
public interface GeneralRequestContext extends RequestContext
{
Request<InitDataProxy> getInitData();
}
But this won't work because I don't want to have to actually back InitDataProxy with anything, I just want to use it to combine a bunch of different types of Proxies in a single request.
So: Is there a way to receive multiple, unrelated types of EntityProxy in a single request?
I would also be happy enough making a normal gwt-rpc request to go outside of RequestFactory for this data, but I don't want to have to implement duplicate DTOs to run next to RequestFactory's proxies, and write custom code to copy the DTOs into them!
The InitDataProxy could extend ValueProxy instead, which doesn't require that the object on the server have any kind of id or version semantics. The domain-side InitData type could be an interface, possibly implemented with an anonymous type.
interface InitData {
User getUser();
Organization getOrgatization();
}
class InitService {
static InitData makeInitData() {
return new InitData() { ..... };
}
}
#ProxyFor(InitData.class)
interface InitDataProxy extends ValueProxy {
UserProxy getUser();
OrganizationProxy getOrganization();
}
#Service(InitService.class)
interface Init extends RequestContext {
Request<InitDataProxy> makeInitData();
}