java - Is it a good practice to make methods "do nothing" based on a condition? -
kind of specific question, take @ this: (bare me, quick made-up java)
public class main { private static list<integer> list = new arraylist<>(); public static void add(int x) { if(list.contains(x)) { return; } list.add(x); } public static void main() { list.add(1); list.add(1); //should nil or throw error? } }
also, please ignore could've used set<integer>
removes need if(list.contains(x))
anyways, assume list
cannot have duplicates, , assume if @ time duplicate accidentally added (ex: sec list.add(1)
) should considered bug; don't want add together duplicates if don't have to.
the bottom line this: should add(int x)
have instead thrown exception (like illegalargumentexception
or something)? understand if didn't, wouldn't need worry causing actual bugs involving duplication since won't on sec add, still bothers me bit @ point unnecessary add()
called.
i have seen code similar add(int x)
checks something, , nil based on that. can apply thought have done before.
anyways, don't know. should go on above in later similar problems, or should have thrown exception?
yes both, depending on want achieve. set, adding non-unique element should nothing, , not exceptional situation. list of unique elements, adding non-unique element might exceptional situation, , should raise exception. it not question of programming, of modeling: object considers normal, , not. there no 1 "best" answer.
for example, if want track developers have had work done today, might add together them worked
set. if developer commit today, , add together him, still "had work done", , not exceptional situation; homecoming without changing list.
but if handling employment records , employ developer while beingness in employ, exceptional situation, , error should raised.
java debugging coding-style
No comments:
Post a Comment