Is it a good practice to execute query in constructor?
class Foo {
public Foo() {
populateData();
}
private void populateData() {
// query database here...
}
}
Constructor only purpose is to create an instance of a class.
The issue with querying a database is the operation can fail.
At that point if you don't handle exception properly then your code is candidate for bugs.
You should think of constructor a way to prepare the object for use which should be quick.
If you want your code to be both legible and extensible, I can advise to consider the Single_responsibility_principle. According to it - every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.
So bottom line is your method to be put to work like this:
public static class DbAccessor
{
public static void setPopulatedData() {
// query database here...
}
}
You could use lazy values. Google Guava provides some utilities to do that.
e.g.
class Foo {
private final Spplier<Data> data = Suppliers.memoize(new Supplier<Data>() {
public Data get() {
// query database here...
return data;
};
});
public Foo() {
}
}
Related
I want to create a class User that will manipulate data on the user table in my database. But I don't know if I should make it a Singleton or just bundle a bunch of static methods.
class UserSingleton {
private static instance;
private UserSingleton() {
// stablish connection and prepare statements
}
public static getInstance() {
if (instance == null) {
instance = new UserSingleton();
}
return instance;
}
public void create() {};
public void delete() {};
// and so on...
}
class UserStatic {
public static initialize() {
// Stablish connection and prepare statements.
// These properties would be static.
}
public static void create() {};
public static void delete() {};
// and so on...
}
I really don't know what would be the best approach here or the pros and cons of each of them. While the singleton class seems more elegant and cool, the static class API would be easier to use since I don't have to instantiate an object. Also it resembles me of mongoose, where such methods are static, e.g: Model.create(), Model.findById(), and so on...
What do you think? Or I should do it in a completely different manner? Some context about the app:
It's a small/medium desktop app made with JavaFX
The database is SQLite
Tests aren't a priority (some people may point out that Singleton is bad because it makes testing harder)
Take a look at JPA, Spring Data with eclipselink as implementation or Hibernate. If it is just for educational purpouses have a look at the spring orm implementaions.
Avoid singletons at any cost
You need to specify your API with interfaces.
It appears that you have Users and User which could be defined like that
interface User {
long id();
String name();
}
interface Users {
Iterable<User> iterate();
User create(String name);
void delete(User user);
Optional<User> findById(long id);
}
Implement these interfaces with plain jdbc or with help of a library such as jOOQ or jcabi-jdbc
Avoid ORM and thinking about your business task in terms of databases and SQL. Use OOP tactics to design your objects and how they work with each other.
I have a class that is essentially a wrapper for a large data object on a database. Looks like this:
public class ServerWrapper {
private DataObject object;
public ServerWrapper(DataObject object) {
this.object = object;
}
public void doAThing1() {
getSomeStuff();
// do stuff that modifies this object
}
public void doAThing2() {
getSomeStuff();
// do other stuff that modifies this object
}
private List<> getSomeStuff();
}
This is the problem: there are many, many "doAThing" methods. And some of them are quite large. Also, a lot of them use other private methods also in ServerWrapper. Ideally, I'd like to break off these public methods into their own classes, like ThingDoer1, ThingDoer2, but I don't know the best way to do this.
Something like this:
public class ThingDoer1{
public void doAThing1(ServerWrapper wrapper) {
wrapper.getSomeStuff();
// do the thing to wrapper
}
seems very smelly; it's tightly coupled to ServerWrapper (ServerWrapper calls it and it calls ServerWrapper), plus it needs to either do stuff with the object it's given (which is bad), or make a copy, do the stuff, then return the copy.
Really, I think what I'm looking for is a set of partial classes, just to make this monster of a class more manageable; but I'm using Java, which doesn't support that.
Is there some standard practice for breaking down a large class like this? Thanks in advance!
EDIT:
The point of the wrapper is to add server-side functionality to a database object. For example, this object needs to be "expired". What this requires is getting all the associations to the database table, then doing several validations on the object and those associations, then setting a bunch of fields in the object and its associations, then calling a database update on the object and all those associations. Having all that code inside the ServerWrapper makes sense to me, but there are several fairly complex operations like that the need to happen, so the class itself is getting rather large.
But it doesn't need to be tightly coupled with ServerWrapper:
public class ThingDoer1() {
public void doAThing1(List<> theList) {
// do the thing to object
}
Then in ServerWrapper:
public void doAThing1() {
new ThingDoer1().doAThing1(getSomeStuff());
}
I'd go further maybe:
public class ThingDoer1() {
private final List<> theList;
public ThingDoer1(List<> theList) {
this.theList = theList;
}
public void doAThing() {
// do the thing to object
}
}
In ServerWrapper:
public void doAThing1() {
new ThingDoer1(getSomeStuff()).doAThing();
}
Which is more of a Replace Method with Method Object refactor.
There's a problem I can't solve. I have simple part of code here:
public class Item{
Block blockDrop;
public void setBlockDrop(Block block) {
this.blockDrop = block;
}
}
public class Block{
Item itemDrop;
public void setItemDrop(Item item) {
this.itemDrop = item;
}
}
public class ItemDirt extends Item {
public ItemDirt() {
setBlockDrop(Registry.blockDirt);
}
}
public class BlockDirt extends Block {
public BlockDirt() {
setItemDrop(Registry.itemDirt);
}
}
public class Registry {
public static ItemDirt itemDirt = new ItemDirt();
public static BlockDirt blockDirt = new BlockDirt();
}
When I run this, blockDirt WILL drop itemDirt, but itemDirt WON'T drop blockDirt. Is there any way I can solve this? I could instead add to Registry constructor:
itemDirt.setBlockDrop(blockDirt);
blockDirt.setItemDrop(itemDirt);
but that defeats whole simplicity of my objects.
The problem is that when ItemDirt is constructed and assigned to Registry.itemDirt, its constructor already uses Registry.blockDirt, although it has not been initialized and is still null at that point of time.
This is a typcial problem that happens when objects try to prematurely grab alien objects at construction time. Usually, a constructor should never 'reach' outside and grab other objects that may or may not exist at that point of time.
There seems to be no pretty way to break your vicious circle without some visible alterations to your code, but maybe something like this will be less ugly:
public class Registry() {
public static ItemDirt itemDirt;
public static BlockDirt blockDirt;
static {
itemDirt = new ItemDirt();
blockDirt = new BlockDirt();
itemDirt.setBlockDrop(blockDirt);
}
}
Or some lazy initializations in your set methods. Your call.
It looks like you're trying to implement something similar to the Mediator Pattern, but the real way to do this is not in the constructor, because you cannot be assured of the order of construction.
Instead, when you implement a business method, you call a Mediator, which then handles the inter-class communication. Please read up on the Mediator Pattern before you go further, as it will provide some insight on how to do this better.
Edit: I am trying to create a shared database connection pool for all sessions of a web application. A different post said the best way to create a servlet context object was by having the init listener create it. I am however unclear on how to make this object available for use by my servlet.
Another way you could do this is use static initialization:
public class SomeClass {
private static final Object[] CONTENT;
static {
CONTENT = new Object[SomeOtherClass.getContentSize()]; // To show you can access runtime variables
}
}
This will initialize the CONTENT array once the class is loaded using the ClassLoader.
One solution is using a private holder class:
public class SomeClass {
private static class ResourceHolder {
private static final Resource INSTANCE = new Resource();
}
public static Resource getInstance() {
return ResourceHolder.INSTANCE;
}
}
the instance will be initialized when SomeClass.getInstance() is called the first time.
The simplest lazy initialisation is to use an enum with one instance.
enum Singleton {
INSTANCE; // lazy initialised
}
The added problem is you want initialisation values. To handle this you can nest the class.
enum Utility {;
static MyType val;
static OtherType val2;
enum Holder {
INSTANCE;
Holder() {
// uses val and val2
}
}
public static Holder getInstance(MyType val, OtherType val2) {
Utility.val = val;
Utility.val2 = val2;
return Holder.INSTANCE; // only created the first time.
}
}
Note: this is thread safe as static block initialisation is safe.
Something like:
public static abstract class Lazy<T> {
private T t = null;
public synchronized T get() {
if (t == null) {
t = create();
}
return t;
}
protected abstract T create();
}
public static final Lazy<List<String>> lazyList = new Lazy<List<String>>(){
#Override
protected List<String> create() {
return new ArrayList<String>();
}
};
I'll caution you up front, what you're describing has a bit of code smell, and I suspect you'll do better to avoid this pattern entirely. A static resource that depends on external runtime state breaks all sorts of best practices about variable scope.
What you're describing, however, would best be implemented by either a Supplier or a Future, depending on the work involved in successfully constructing the object you need. The difference is somewhat pedantic, but you'd generally use a Future to hold a reference that will take a long time to compute, while a Supplier generally returns quickly. Future also has some nice hook-ins with Java's concurrency utilities, but by the sound of it you don't need that.
You'd use a Supplier like so:
public class GlobalState {
public static final Supplier<LazyData> MY_DATA = Suppliers.memoize(
new Supplier<LazyData>() {
public LazyData get() {
// do whatever you need to construct your object, only gets executed once needed
}
});
...
}
Suppliers.memoize() will cache the result of the first call to the underlying Supplier in a threadsafe way, so simply wrapping the Supplier you define with this call prevents duplicate processing.
Example:
public class TestClass {
public static void main(String[] args) {
TestClass t = new TestClass();
}
private static void testMethod() {
abstract class TestMethod {
int a;
int b;
int c;
abstract void implementMe();
}
class DummyClass extends TestMethod {
void implementMe() {}
}
DummyClass dummy = new DummyClass();
}
}
I found out that the above piece of code is perfectly legal in Java. I have the following questions.
What is the use of ever having a class definition inside a method?
Will a class file be generated for DummyClass
It's hard for me to imagine this concept in an Object Oriented manner. Having a class definition inside a behavior. Probably can someone tell me with equivalent real world examples.
Abstract classes inside a method sounds a bit crazy to me. But no interfaces allowed. Is there any reason behind this?
This is called a local class.
2 is the easy one: yes, a class file will be generated.
1 and 3 are kind of the same question. You would use a local class where you never need to instantiate one or know about implementation details anywhere but in one method.
A typical use would be to create a throw-away implementation of some interface. For example you'll often see something like this:
//within some method
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});
If you needed to create a bunch of these and do something with them, you might change this to
//within some method
class myFirstRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
}
class mySecondRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomethingElse( parameter );
}
}
taskExecutor.execute(new myFirstRunnableClass());
taskExecutor.execute(new mySecondRunnableClass());
Regarding interfaces: I'm not sure if there's a technical issue that makes locally-defined interfaces a problem for the compiler, but even if there isn't, they wouldn't add any value. If a local class that implements a local interface were used outside the method, the interface would be meaningless. And if a local class was only going to be used inside the method, both the interface and the class would be implemented within that method, so the interface definition would be redundant.
Those are called local classes. You can find a detailed explanation and an example here. The example returns a specific implementation which we doesn't need to know about outside the method.
The class can't be seen (i.e. instantiated, its methods accessed without Reflection) from outside the method. Also, it can access the local variables defined in testMethod(), but before the class definition.
I actually thought: "No such file will be written." until I just tried it: Oh yes, such a file is created! It will be called something like A$1B.class, where A is the outer class, and B is the local class.
Especially for callback functions (event handlers in GUIs, like onClick() when a Button is clicked etc.), it's quite usual to use "anonymous classes" - first of all because you can end up with a lot of them. But sometimes anonymous classes aren't good enough - especially, you can't define a constructor on them. In these cases, these method local classes can be a good alternative.
The real purpose of this is to allow us to create classes inline in function calls to console those of us who like to pretend that we're writing in a functional language ;)
The only case when you would like to have a full blown function inner class vs anonymous class ( a.k.a. Java closure ) is when the following conditions are met
you need to supply an interface or abstract class implementation
you want to use some final parameters defined in calling function
you need to record some state of execution of the interface call.
E.g. somebody wants a Runnable and you want to record when the execution has started and ended.
With anonymous class it is not possible to do, with inner class you can do this.
Here is an example do demonstrate my point
private static void testMethod (
final Object param1,
final Object param2
)
{
class RunnableWithStartAndEnd extends Runnable{
Date start;
Date end;
public void run () {
start = new Date( );
try
{
evalParam1( param1 );
evalParam2( param2 );
...
}
finally
{
end = new Date( );
}
}
}
final RunnableWithStartAndEnd runnable = new RunnableWithStartAndEnd( );
final Thread thread = new Thread( runnable );
thread.start( );
thread.join( );
System.out.println( runnable.start );
System.out.println( runnable.end );
}
Before using this pattern though, please evaluate if plain old top-level class, or inner class, or static inner class are better alternatives.
The main reason to define inner classes (within a method or a class) is to deal with accessibility of members and variables of the enclosing class and method.
An inner class can look up private data members and operate on them. If within a method it can deal with final local variable as well.
Having inner classes does help in making sure this class is not accessible to outside world. This holds true especially for cases of UI programming in GWT or GXT etc where JS generating code is written in java and behavior for each button or event has to be defined by creating anonymous classes
I've came across a good example in the Spring. The framework is using concept of local class definitions inside of the method to deal with various database operations in a uniform way.
Assume you have a code like this:
JdbcTemplate jdbcOperations = new JdbcTemplate(this.myDataSource);
jdbcOperations.execute("call my_stored_procedure()")
jdbcOperations.query(queryToRun, new MyCustomRowMapper(), withInputParams);
jdbcOperations.update(queryToRun, withInputParams);
Let's first look at the implementation of the execute():
#Override
public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
/**
* Callback to execute the statement.
(can access method local state like sql input parameter)
*/
class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider {
#Override
#Nullable
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
#Override
public String getSql() {
return sql;
}
}
//transforms method input into a functional Object
execute(new ExecuteStatementCallback());
}
Please note the last line. Spring does this exact "trick" for the rest of the methods as well:
//uses local class QueryStatementCallback implements StatementCallback<T>, SqlProvider
jdbcOperations.query(...)
//uses local class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider
jdbcOperations.update(...)
The "trick" with local classes allows the framework to deal with all of those scenarios in a single method which accept those classes via StatementCallback interface.
This single method acts as a bridge between actions (execute, update) and common operations around them (e.g execution, connection management, error translation and dbms console output)
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
//
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
Everything is clear here but I wanted to place another example of reasonable use case for this definition type of class for the next readers.
Regarding #jacob-mattison 's answer, If we assume we have some common actions in these throw-away implementations of the interface, So, it's better to write it once but keep the implementations anonymous too:
//within some method
abstract class myRunnableClass implements Runnable {
protected abstract void DO_AN_SPECIFIC_JOB();
public void run() {
someCommonCode();
//...
DO_AN_SPECIFIC_JOB();
//..
anotherCommonCode();
}
}
Then it's easy to use this defined class and just implement the specific task separately:
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do something
}
});
taskExecutor.execute(new myRunnableClass() {
protected void DO_AN_SPECIFIC_JOB() {
// Do another thing
}
});