I am aware of this answer that explains what setting lazy="extra" does.
My question is, is there any costs associated with using lazy="extra"? Why wouldn't we just set lazy="extra" to every instance where we would otherwise set it to "true"? It seems it is same as "true" but better?
The only thing I can think of is that if a collection is mostly used as data source or for iterating on a loop it would be better to get the full collection first time you access ANY property (even Count).
Otherwise you might end up executing more queries than necessary.
For example
bool found = false;
int pos = 0;
while (!found && pos < Collection.Count)
{
if (MyFunction(Collection[pos]))
{
found = true;
}
pos++;
}
Related
I am not getting an efficient way to check below mentioned condition.
What I want to achieve is that-
There are some processes that need to be done if their corresponding boolean is true suggesting to start the process. So I want to check if a particular condition is done only if it should be started.
There are some boolean variables
var shouldStartProcessA
var shouldStartProcessB
var shouldStartProcessC
var isADone
var isBDone
var isCDone
if (shouldStartProcessA && shouldStartProcessB && shouldStartC) {
if (isADone && isBDone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessA && shouldStartProcessB) {
if (isADone && isBDone) {
// Every process completed
}
}
if (shouldStartProcessA && shouldStartC) {
if (isADone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessB && shouldStartC) {
if (isBDone && isCDone) {
// Every process completed
}
}
if (shouldStartProcessA) {
if (isADone) {
// Every process completed
}
}
if (shouldStartProcessB) {
if (isBDone) {
// Every process completed
}
}
if (shouldStartProcessC) {
if (isCDone) {
// Every process completed
}
}
This type of validating condition grows exponentially by introducing every other boolean. I am struggling to find a straightforward implementation to check these conditions.
Instead of doing things this way, I'd recommend a data structure that allows you to add tasks and check their state. There are a lot of ways to do that, but the basic idea is you can iterate over all the items and use functions like all to confirm they're all in the appropriate state. That way you don't have to hand-wire everything together
You could use a Map and add tasks to it, initially mapping them to false and setting that to true when they're completed. Or create a Set and add your tasks to that (I'm assuming you want one of each at most), and remove them / move them to a "done" list when they complete. That kind of idea. You could create an enum class to represent your tasks if you want, so each one is its own instance (e.g. Process.A, like having a dedicated, fixed variable) and you can easily use those in your logic
If you really want variables for each process, instead of a data structure, I'd still recommend rolling each pair into a single state, something like this:
enum class State {
UNUSED, PENDING, DONE
}
var processA = State.UNUSED
var processB = State.PENDING
// etc
// you can easily check them like this:
// create a list of all the variables you want to check - we're using references
// to the properties themselves (with the ::), not the current value!
val allProcesses = listOf(::processA, ::processB)
// now you have that collection, you can easily iterate over them all
// and work out what's what - we need to use get() to get the current values
val allFinished = allProcesses
.filterNot { it.get() == State.UNUSED } // ignore unused processes
.all { it.get() == State.DONE } // check ALL the required ones are DONE
You could write that check there as a single all condition, but the point is to show you you can be flexible with it, and build up your logic by filtering out the stuff you're not interested in, if you create a useful set of states
If you really do want to (or have to) stick with the current "pairs of variables" setup, you can do something similar:
// wiring them up again, creating a list of Pairs so we can iterate over them easily
val allProcesses = listOf(
::shouldStartProcessA to ::isADone,
::shouldStartProcessB to ::isBDone,
::shouldStartProcessC to ::isCDone
)
// gotta check 'em all - only returns true if that ALL meet the condition
val allComplete = allProcesses.all { (shouldStart, isDone) ->
// the get() syntax is awkward, but basically for everything we're checking
// if it either doesn't need to start, or it does but it's also done
!shouldStart.get() || (shouldStart.get() && isDone.get())
}
so adding new processes is just a case of adding their variables to the list of pairs, and they get included in the checking
You don't need the property reference stuff (::/.get()) if you create the lists right before you check them, but if you want to define them once in advance (and the property values can change after that) then that's how you'd do it. Otherwise you can just do the normal shouldStartProcessA to isADone etc, which is probably fine for most cases - I'm showing the reference stuff as a more general example for handling this kind of thing
I suppose, you should create two lists of Boolean and add variables consequently.
val list1 = listOf(shouldStartProcessA, shouldStartProcessB, shouldStartC)
val list2 = listOf(isADone, isBDone, isCDone)
Then iterate over both lists and check that items in corresponding positions have the same values.
var n = 0
for (i in list1.indices) {
if (list1[i] == list2[i]) {
n++
} else {
n = 0
break
}
}
if (n > 0) {
// Every process completed
}
I'm trying to iterate through a set to find an item. If the item is found, I want it to print a certain message and another message if item is not found. So far, it works but it print a message for each item on the set, whereas I only want one message to display: either if the item was found with the price or the message that it wasn't found. I understand this is happening because of the for loop but I'm not sure how to get it to display the not found message only once and iterate through the set all the same.
This is the code:
fun getArticleOut(code:String) {
fun onSuccess(price: Int): String {
return "Price is $price"
}
fun onError(): String {
return "Article not found"
}
for (i in house.articles) {
if (i.code.equals(code)) {
val price = calculatePrice(
articleType = i.articleType,
totalTime = i.totalTime.toInt(),
hasCard = !i.hasCard.isNullOrEmpty()
)
println(onSuccess(price))
house.articles.remove(i)
} else {
println(onError())
}
}
}
Just to clarify:
data class House(val articles: MutableSet<Articles>)
data class Articles(val code: String,
var articleType: ArticleType,
var totalTime: Calendar,
var hasCard:String?=" ")
The direct answer is the break statement, which breaks out of a for or while loop. You'd then have to move the onError() call outside the loop, with some way of telling whether the loop completed or not. For example:
var found = false
for (i in house.articles) {
if (i.code == code) {
val price = calculatePrice(
articleType = i.articleType,
totalTime = i.totalTime.toInt(),
hasCard = !i.hasCard.isNullOrEmpty())
println(onSuccess(price))
house.articles.remove(i)
found = true
break
}
}
if (!found)
println(onError())
If you don't need to do anything after both cases (as in the code in question), then you could simplify it to return, and avoid the flag:
for (i in house.articles) {
if (i.code == code) {
val price = calculatePrice(
articleType = i.articleType,
totalTime = i.totalTime.toInt(),
hasCard = !i.hasCard.isNullOrEmpty())
println(onSuccess(price))
house.articles.remove(i)
return
}
}
println(onError())
However, there are probably better approaches that don't need manual iteration. Kotlin's standard library is so powerful that any time you find yourself writing a loop, you should stop and ask whether there's a library function that would make it simpler.
In particular, you could use find(), e.g.:
val article = house.articles.find{ it.code == code }
if (article != null) {
val price = calculatePrice(
articleType = article.articleType,
totalTime = article.totalTime.toInt(),
hasCard = !article.hasCard.isNullOrEmpty())
println(onSuccess(price))
house.articles.remove(article)
} else {
println(onError())
}
That makes the code easier to read, too. (Note that the code is now saying what it's doing, not how it's doing it, which is usually an improvement.)
There are also deeper design questions worth asking, which could lead to further simplifications. For example:
If code is a unique identifier for Article, another option would be to make articles a Map from code to the corresponding Article; both checking and removal would then be constant-time operations, so more efficient as well as more concise. (Of course, that depends on how often you're doing these lookups, and what else is setting or using articles.)
Or you could override Article.equals() to check only the code. Then you could create a dummy Article with the code you're looking for, and do a simple in test (which uses the set's contains method) to check for its presence. Accessing and removing the ‘true’ one in the set would be harder, though, so that may not be a good fit.
Would be neater for calculatePrice() to be defined to take an Article directly? (Obviously that depends on whether it could be calculating the price of anything else too.) Could it even be a method or extension function on Article? (That probably depends whether the price is conceptually a property of the article itself, or whether it's specific to the getArticleOut() function and any surrounding code.)
Also worth pointing out that the code in the question has a nasty bug (which all these changes also work around), which is that it's trying to modify a collection while iterating through it, which is dangerous!
If you're lucky, you'll get an immediate ConcurrentModificationException showing you exactly what went wrong; if you're less lucky it'll continue but do something unexpected, such as skipping over an element or giving an apparently-unrelated error later on…
Which is another reason to avoid manual iteration where possible.
(The only safe way to remove an element while iterating is to manage the Iterator yourself, and use that to do the removal.)
My old function in objective c is
+ (NSUInteger)getNumberOfDistinctUsers:(NSArray *)users {
NSArray* usersAfterPredicate = [users valueForKeyPath:#"#distinctUnionOfObjects.userName"];
return [usersAfterPredicate count]; }
How do I convert this in swift, I was trying to something like this but its crashing "Could not cast value of type 'Swift.Array'to 'Swift.AnyObject'"
static func getNumberOfDistinctUsers(users: [ICEPKReferenceDataUser]) -> Int {
var retval : Int = 0
if let usersAfterPredicate = (users as! AnyObject).valueForKeyPath("#distinctUnionOfObjects.userName") {
retval = usersAfterPredicate.count
}
return retval
}
Can I solve this problem using filter, map or Reduce? I am just trying to find out distint users in users array using the property username.
Edit* brute force way
static func getNumberOfDistinctUsers(users: [ICEPKReferenceDataUser]) -> Int {
var retvalSet : Set<String> = []
for user in users {
retvalSet.insert(user.userName)
}
return retvalSet.count
}
As you suspect, you can simplify the code with a simple map:
static func getNumberOfDistinctUsers(users: [ICEPKReferenceDataUser]) -> Int {
return Set(users.lazy.map{$0.userName}).count
}
This uses the fact that you can initialize a Set using any other sequence.
I added lazy in there to avoid creating an extra copy of the array. It'll work with or without, but I expect it to be much more memory efficient this way. Array.map creates another Array. array.lazy.map return a lazy collection that computes values as requested.
That said, I don't know that my approach is dramatically better than your "brute-force" way. It's not obvious which is easer to read or maintain. I have a fondness for the map approach, but it can be a tradeoff (I had to know to add lazy for instance, or I could have allocated significant memory if this were a large array). Your code makes it very clear what's going on, so I don't think there's any problem that has to be solved there.
If you really wanted to use KVC, you'd need to convert your array to an NSArray, not an AnyObject, but I suspect that the above code is much faster, and is clearer and simpler, too, IMO.
I have a rad grid bound to a collection of custom objects and occasionally I grab a rows index like this:
e.Item.ItemIndexHierarchical
at some point later when I want to retrieve that item (if it still exists) I use this:
gvAgendaItems.Items(HierarchicalIndexKey)
The problem is that sometimes the item doesn't exist anymore - and I'm OK with that - but I'd like to gracefully skip over the section of code that is working on the items it can find. As it stands, searching for an item using a no longer valid key throws an exception so I can't just check if the resulting item is nothing.
How can I test if that HierarchicalIndexKey is still valid without throwing an exception?
I don't see any elegant ways to do this in the Telerik documentation (leaving only blunt/inefficient ways, unfortunately).
You could loop through the items and match the HierarchicalIndexKey on each item's ItemIndexHierarchical:
int i = 0;
bool bIndexExists = false;
GridDataItem item = null;
for (i = 0; i <= gvAgendaItems.Items.Count - 1; i++) {
bIndexExists = gvAgendaItems.Items(i).ItemIndexHierarchical == HierarchicalIndexKey;
if (bIndexExists) {
item = gvAgendaItems.Items(HierarchicalIndexKey);
break;
}
}
You could wrap it in a Try/Catch block and simply fail silently.
GridDataItem item = null;
try {
item = gvAgendaItems.Items(HierarchicalIndexKey);
} catch (Exception ex) {
//fail silently without throwing an exception.
}
Looping will be more efficient with smaller datasources, where as wrapping will be more efficient with larger datasources (the breakpoint is when it takes more time to loop through the collection than it does to throw an exception).
Wish I had a better answer, but I hope this helps.
I'm trying to demonstrate invariants in Code Contracts, and I thought I'd give an example of a sorted list of strings. It maintains an array internally, with spare space for additions etc - just like List<T>, basically. When it needs to add an item, it inserts it into the array, etc. I figured I had three invariants:
The count must be sensible: non-negative and at most as big as the buffer size
Everything in the unused part of the buffer should be null
Each item in the used part of the buffer should be at least as "big" as the item before it
Now, I've tried to implement that in this way:
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(count >= 0 && count <= buffer.Length);
for (int i = count; i < buffer.Length; i++)
{
Contract.Invariant(buffer[i] == null);
}
for (int i = 1; i < count; i++)
{
Contract.Invariant(string.Compare(buffer[i], buffer[i - 1]) >= 0);
}
}
Unfortunately, ccrewrite is messing up the loops.
The user documentation says that the method should just be a series of calls to Contract.Invariant. Do I really have to rewrite the code as something like this?
Contract.Invariant(count >= 0 && count <= buffer.Length);
Contract.Invariant(Contract.ForAll
(count, buffer.Length, i => buffer[i] == null));
Contract.Invariant(Contract.ForAll
(1, count, i => string.Compare(buffer[i], buffer[i - 1]) >= 0));
That's somewhat ugly, although it does work. (It's much better than my previous attempt, mind you.)
Are my expectations unreasonable? Are my invariants unreasonable?
(Also asked as a question in the Code Contracts forum. I'll add any relevant answers here myself.)
From the (preliminary) MSDN pages it looks like the Contract.ForAll member could help you with the 2 range contracts. The documentation isn't very explicit about its function though.
//untested
Contract.Invariant(Contract.ForAll(count, buffer.Length, i => buffer[i] == null));
Contract.Invariant(Contract.ForAll(1, count,
i => string.Compare(buffer[i], buffer[i - 1]) >= 0));
(I'm going to accept Henk's answer, but I think it's worth adding this.)
The question has now been answered on the MSDN forum, and the upshot is that the first form isn't expected to work. Invariants really, really need to be a series of calls to Contract.Invariant, and that's all.
This makes it more feasible for the static checker to understand the invariant and enforce it.
This restriction can be circumvented by simply putting all the logic into a different member, e.g. an IsValid property, and then calling:
Contract.Invariant(IsValid);
That would no doubt mess up the static checker, but in some cases it may be a useful alternative in some cases.
Aren't the designers reinventing the wheel a bit?
What was wrong with the good old
bool Invariant() const; // in C++, mimicking Eiffel
?
Now in C# we don't have const, but why can't you just define an Invariant function
private bool Invariant()
{
// All the logic, function returns true if object is valid i.e. function
// simply will never return false, in the absence of a bug
}
// Good old invariant in C#, no special attributes, just a function
and then just use the Code Contracts in terms of that function?
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(Invariant() == true);
}
Maybe I'm writing nonsense, but even in that case it will have some didactic value when everybody tells me wrong.