Is there anything like type inference in Apex? - type-inference

Working my way through Salesforce Trailhead code modules feels like stepping back in time (having spent the last few years working in c# and JavaScript), is there anything (a tool or modern compiler/runtime) that can infer type specifically for things like for loops like this?
List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'Siebel'];
for(Account a : accs){
a.Name = 'Oracle';
}

You can look at the generic SObject class SObjectType class and getDescribe() calls. Also looking at Dynamic Apex might get you closer to what you are looking for. But still there are alot of limitation with the language.

Related

How to prevent empty list errors in in clause in sql?

One common problem we have in our codebase is that people forget to check if a list is empty before using it in an in clause.
For example (in Scala with Anorm):
def exists(element: String, list: List[String]): Boolean =
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
This code works perfectly well as long as list has at least one element.
If it has 0 elements, you get a syntax error, which is weird if you're used to other programming languages that would allow this empty list case.
So, my question is: what's the best way to prevent this error from happening?
Initially, we did this:
def exists(element: String, list: List[String]): Boolean =
if (list.nonEmpty) {
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
} else {
false
}
This works perfectly well, and has the added advantage that it doesn't hit the database at all.
Unfortunately, we don't remember to do this every time, and it seems that 1-2 times a month we're fixing an issue related to this.
An alternate solution we came up with was to use a NonEmptyList class instead of a standard List. This class must have at least one element. This works excellent, but again, people have not been diligent with always using this class.
So I'm wondering if there's an approach I'm missing that prevent this type of error better?
It looks like you've already found a way to resolve this problem - you have an exists() function which handles an empty list cleanly. The problem is that people are writing their own exists() functions which don't do that.
You need to make sure that your function is accessible as a utility function, so that you can reuse it whenever you need to, rather than having to rewrite the function.
Your problem is an encapsulation problem: the Anorm API is like an open flame and people can burn themselves. If you rely just on people to take precautions, someone will get burnt.
The solution is to restrict the access to the Anorm API to a limited module/package/area of your code:
Anorm API will be private and accessible only from very few places, where it is going to be easy to perform the necessary controls. This part of the code will expose an API
Every other part of the code will need to go through that API, effectively using Anorm in the "safe" way

Math Parser/Lexer - Token interface design

Currently working on a small pet project, a Math Parser/Lexer and eventually solver for fun/learning. I've bashed out a basic prototype and am now looking to convert this into TypeScript to clean things up. Prototype can be found here https://github.com/chips5k/math-solver-prototype for those interested.
I am trying to come up with a clean interface based approach to dealing with my Tokens. I suspect i am looking at this the wrong way, but hopefully someone can offer useful advice.
In my TS design i have several interfaces, the base interface being Token, with NumericToken and FunctionToken extending these. I then have several classes that implement these interfaces such as: AdditionToken, VariableToken, NumberToken, PiToken, SineToken etc...
My problem is that in order to work with these interfaces i end up requiring methods to check the basic type e.g isNumeric, isFunction, isVariable or alternatively a direct type === TokenFactory.NUMERIC etc... This, to me, feels wrong as it basically voids the point of using an interface. I suspect that there is a nicer/cleaner more polymorphic approach i could take but unfortunately i'm out of ideas and have been unable to find info on what i am doing.
An example of where things fall apart shows itself when attempting to solve a series of tokens:
if(t.isFunction()) {
var a = stack.unshift();
var b = stack.unshift();
if(a.isNumeric() && b.isNumeric()){
result.push(tokenFactory.create(t.evaluate<number>(a.evaluate<number>, b.evaluate<number>));
} else {
//return to stack and move on, e.g can't solve x + 1 directly
}
} else {
stack.push(t);
}
Basically looking for what is considered the ideal approach for handling a scenario like this, and i suspect it may be an alternate approach to the design.
TIA!
basic type e.g isNumeric, isFunction, isVariable or alternatively a direct type === TokenFactory.NUMERIC etc... This, to me, feels wrong
Nope. This is fairly idiomatic as the type controls what functionality is there.
E.g you will see the TypeScript checker.ts littered with check on .kind (SyntaxKind) which is at TypeScript AST nodes discriminator.
Also you might want to consider adding a visitor that is recursive e.g.
function visit(item){
if (item.addition) {
return visit(item.left) + visit(item.right)
}
if (item.literal) {
return literal.value();
}
// ETC.
}

PyQt - Use SQL directly with QSqlTableModel

I'm writing a simple student scores manager for practicing programming on PyQt (I don't want to use terrible Visual Basic anymore). But I had a big problem on choose data models.
I found QSqlTableModel first, it is a great model with auto-updating. The trouble is, I need to use a lot of SQL (JOIN, WHERE) to select data from database. QSqlTableModel has select() and filter() only.
Then I found QSqlQueryModel, but it is read only. So I rewrite its setData() method. So it is read-write now. Unfortunately, QSqlQueryModel less usable features than QSqlTableModel.
As you see, if I can using SQL with QSqlTableModel, I can resolve all my problems.
So...?
QSqlTableModel has the setQuery method, which you can use to set a custom query, something like:
model = QSqlTableModel()
query = QSqlQuery(your_query)
model.setQuery(query)
However, the Qt documentation states:
This function simply calls QSqlQueryModel::setQuery(query). You should normally not call it on a QSqlTableModel. Instead, use setTable(), setSort(), setFilter(), etc., to set up the query.

Proper error propagation in clojure

I'm currently working on my first major project in clojure and have run into a question regarding coding style and the most "clojure-esque" way of doing something. Basically I have a function I'm writing which takes in a data structure and a template that the function will try to massage the data structure into. The template structure will look something like this:
{
:key1 (:string (:opt :param))
:key2 (:int (:opt :param))
:key3 (:obj (:tpl :template-structure))
:key4 (:list (:tpl :template-structure))
}
Each key is an atom that will be searched for in the given data structure, and it's value will be attempted to be matched to the type given in the template structure. So it would look for :key1 and check that it's a string, for instance. The return value would be a map that has :key1 pointing to the value from the given data structure (the function could potentially change the value depending on the options given).
In the case of :obj it takes in another template structure, and recursively calls itself on that value and the template structure, and places the result from that in the return. However, if there's an error I want that error returned directly.
Similarly for lists I want it to basically do a map of the function again, except in the case of an error which I want returned directly.
My question is what is the best way to handle these errors? Some simple exception handling would be the easiest way, but I feel that it's not the most functional way. I could try and babysit the errors all the way up the chain with tons of if statements, but that also doesn't seem very sporting. Is there something simple I'm missing or is this just an ugly problem?
You might be interested in schematic, which does pretty similar stuff. You can see how it's used in the tests, and the implementation.
Basically I defined an error function, which returns nil for correctly-formatted data, or a string describing the error. Doing it with exceptions instead would make the plumbing easier, but would make it harder to get the detailed error messages like "[person: [first_name: expected string, got integer]]".

Fluent NHibernate RegisterFunction SQLFunctionTemplate usage

I've seen this opportunity reported at least half a dozen times with about as many responses.
My problem is, I've got a MySQL database function defined, we'll call it "my_func(int val) returns int", which works fine if I test directly on the database.
I've also gotten it to work with a direct SQL passthrough my repository implementation, which is okay, but I'd rather route it through Hql, for some god-awful reason...
So... I've got a MySQL5Dialect setup to register the function and I'm having some difficulty parsing through the expected conventions.
My understanding is that I need to prefix the function name with "dbo." at some point during the function registration?
Something like this,
//...
RegisterFunction("my_func", new SQLFunctionTemplate(NHibernateUtil.Int32, "my_func(?1)"));
//...
And then through my repository,
var value = repository.FindByHQL<int>("select my_func(2)").Single();
Where FindByHQL returns an IList.
Any thoughts why this wouldn't work.
I'm running the latest WAMP (2.1e I think).
Enough info? Let me know if I can provide any further details.
Thanks,
Michael
select my_func(2)
is not valid HQL, regardless of whether the function is registered or not.
You can use SQL instead if that's your use case.
Post full exception with stack trace if it's not and this was just a simplified example.